package com.cykj.pos.service.impl;

import cn.hutool.core.lang.Console;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.common.utils.uuid.UUID;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.*;
import com.cykj.pos.domain.epsp.protocol.ProtocolPayBindCardConfirmResponse;
import com.cykj.pos.domain.epsp.protocol.ProtocolPayBindCardResponse;
import com.cykj.pos.domain.posone.PosOneMerchantInfo;
import com.cykj.pos.domain.vo.BizGdbArea;
import com.cykj.pos.domain.vo.BizMerchParentRelated;
import com.cykj.pos.domain.vo.MerchantDetailDTO;
import com.cykj.pos.domain.vo.PartnerDetailDTO;
import com.cykj.pos.mapper.*;
import com.cykj.pos.profit.dto.MerchantDTO;
import com.cykj.pos.service.*;
import com.cykj.pos.util.*;
import com.cykj.pos.websocket.server.WebSocketServer;
import com.cykj.system.mapper.SysUserMapper;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 商户基本信息Service业务层处理
 *
 * @author xuxiaolong
 * @date 2022-08-09
 */
@Service
public class BizMerchantInfoServiceImpl extends ServiceImpl<BizMerchantInfoMapper, BizMerchantInfo> implements IBizMerchantInfoService {

    @Resource
    private IBizMerchantInfoService bizMerchantInfoService;

    @Resource
    private BizMerchantInfoMapper bizMerchantInfoMapper;

    @Resource
    private IBizPosMachineService posMachineService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Resource
    private IBizMerchantService bizMerchantService;

    @Resource
    private BizMerchantEntryMapper bizMerchantEntryMapper;

    @Resource
    private IBizMerchantService iBizMerchantService;
    @Resource
    private IBizMerchTransactionsService BizMerchTransactionsService;
    @Resource
    private IBizPosMachineStatusRecordsService machineStatusRecordsService;
    @Resource
    BizPosMachineStatusRecordsMapper machineStatusRecordsMapper;
    @Resource
    private IBizPosMachineStatusRecordsService recordsService;
    @Resource
    private PosPCommonParamConfig PosPCommonParamConfig;
    @Resource
    private IPosTransactionNoticeService posTransactionNoticeService;

    @Resource
    private IBizMerchantEpspBindingService iBizMerchantEpspBindingService;
    @Resource
    BizPosMachineMapper bizPosMachineMapper;
    @Resource
    private BizPosMachineStatusRecordsMapper bizPosMachineStatusRecordsMapper;
    //默认费率0.6
    private Integer DEFAULT_FEE_ID=10001;

    @Resource
    private IBizMicroInfoService bizMicroInfoService;

    @Resource
    private BizTransactionAmountServiceImpl bizTransactionAmountServicImpl;


    @Resource
    private IPosBindActiveRecordsService iPosBindActiveRecordsService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private IBizWalletNewService iBizWalletNewService;


    @Resource
    private UnFailureActiveTemplateMapper unFailureActiveTemplateMapper;

    @Autowired
    private IAllocationRelationService iAllocationRelationService;

    @Autowired
    private IAizStatisticalMerchantService iAizStatisticalMerchantService;

    @Autowired
    private PosTransactionNoticeMapper posTransactionNoticeMapper;

    @Override
    public List<BizMerchantInfo> queryList(BizMerchantInfo bizMerchantInfo) {
        //当前时间
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> data= bizMerchantInfo.getParams();
        if (!data.isEmpty()){
            //map获取方式：Object beginTime=data.get("key");
            //获取data的beginTime和endTime
            Object beginTime=data.get("beginTime");
            Object endTime=data.get("endTime");
            //beginTime和endTime转换成string
            String beginTimestr= beginTime.toString();
            String endTimestr= endTime.toString();
            //放入到bizMerchTransactions里
            bizMerchantInfo.setBeginTime(beginTimestr+" 00:00:00");
            bizMerchantInfo.setEndTime(endTimestr+ " 23:59:59");
            bizMerchantInfo.setBeginTime1(beginTimestr.replace("-",""));
            bizMerchantInfo.setEndTime1(endTimestr.replace("-",""));
        }
        List<BizMerchantInfo> list = bizMerchantInfoMapper.queryList(bizMerchantInfo);
        return list;
    }

    @Override
    @Transactional
    public JSONObject addMerchantsInfo(BizMerchantInfo bizMerchantInfo) {
        JSONObject legalPerson = new JSONObject();
        String posCode = bizMerchantInfoMapper.selectMerchantInfoSn(bizMerchantInfo.getPosCode());
        if (StringUtils.isNotBlank(posCode)) {
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "已存在商户");
            return  erro;
        }
        BizPosMachine posMachineBySnCode = posMachineService.getPosMachineBySnCode(bizMerchantInfo.getPosCode());
        if(posMachineBySnCode == null){
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "设备不存在");
            return  erro;
        }
        // 代理
        BizMerchant merchantByMerchId = bizMerchantService.getMerchantByMerchId(posMachineBySnCode.getMerchId());

//        BizMerchantInfo bizMerchantInfo1 =  bizMerchantInfoMapper.selectMerchantInfoByCertificateNoAndSn(bizMerchantInfo);
//        if (bizMerchantInfo1 != null){ //删除进件失败的
//            bizMerchantInfoMapper.deleteMerchantInfoById(bizMerchantInfo1.getId());
//        }
        legalPerson.put("certificateEndDate", bizMerchantInfo.getCertificateEndDate()); //  证件有效期截止日期（例：1949-10-01）;
        legalPerson.put("certificateNo", bizMerchantInfo.getCertificateNo());   //  法人证件号码
        legalPerson.put("certificateStartDate", bizMerchantInfo.getCertificateStartDate()); //  证件有效期开始日期（例：1949-10-01）
        //暂时写死
        //  legalPerson.put("certificateType", Byte.decode("1")); //  法人证件类型,1：身份证,2：港澳通行证,3：台湾身份证,4：HK身份证,5：MC身份证,6：护照,7：居住证,9：其他法定证件（如提供身份证以外资料，进件时将转人工审核）（调用修改时不需要传入该字段）
        legalPerson.put("certificatesBackPic", bizMerchantInfo.getCertificatesBackPic()); //  证件国徽面
        legalPerson.put("certificatesFrontPic", bizMerchantInfo.getCertificatesFrontPic()); //  证件人脸面
        legalPerson.put("idcardHandPic", bizMerchantInfo.getIdcardHandPic()); //  手持身份证照片（与法人人脸识别留存照片两者必须有一个不为空）; 例如:picture2/手持身份证照片.jpg
        legalPerson.put("legalPersonName", bizMerchantInfo.getLegalPersonName()); //  法人姓名
        JSONObject merchantInfo = new JSONObject();
        //转成数组
        List<String> productType = new ArrayList<>();
        //暂时写死
        //  productType.add("POS");
        legalPerson.put("address", bizMerchantInfo.getAddress()); //  详细地址
        //通用一个人
        legalPerson.put("applicant", bizMerchantInfo.getLegalPersonName()); //  联系人（固定为法人名称
        legalPerson.put("areaNo", bizMerchantInfo.getAreaNo()); //  区县代码
        legalPerson.put("cityNo", bizMerchantInfo.getCityNo()); //   城市编号
        legalPerson.put("provinceName", bizMerchantInfo.getProvinceName()); //   城市编号
        legalPerson.put("cityName", bizMerchantInfo.getCityName()); //   城市编号
        legalPerson.put("areaName", bizMerchantInfo.getAreaName()); //   城市编号
        legalPerson.put("clientServicePhoneNo", bizMerchantInfo.getClientServicePhoneNo()); //   客服电话
        legalPerson.put("contactPhoneNo", bizMerchantInfo.getContactPhoneNo()); //  联系电话
        // mcc码暂时先这么写  mcc = 4812
        // merchantInfo.put("mccCode", "4812"); //  所属行业mcc码
        legalPerson.put("merchantName", bizMerchantInfo.getLegalPersonName()); //  商户名称（固定格式：前缀”商户_“+法人名称）
        BizPosLsMcc mccVo=bizMerchantInfoMapper.getlsIndustry(bizMerchantInfo.getMcc());
        legalPerson.put("merchantShortHand", bizMerchantInfo.getMerchantShortHand()); //  商户简写 app传的
        legalPerson.put("mccCode",mccVo.getMcc());
        //暂时写死
        // merchantInfo.put("merchantSubType", "4"); //  商户子类型：1：小微A;2：小微B;3：小微C;4：小微D
        //暂时写死了
        //  merchantInfo.put("merchantType", Byte.decode("1")); //  商户类型,1：个人,2：个体,3：企业(调用修改时不需要传入该字段）
        //  merchantInfo.put("productType", productType); //  array	申请产品类型;例["SHOUSHUA","POS"] 具体类型：POS,SAOMA,SHOUSHUA
        legalPerson.put("provinceNo", bizMerchantInfo.getProvinceNo()); //  省份代码（调用修改时不需要传入该字段）
        JSONObject settleAccountInfo = new JSONObject();
        legalPerson.put("bankCardAccount", bizMerchantInfo.getBankCardAccount()); //  银行账号
        legalPerson.put("bankCardHolder", bizMerchantInfo.getBankCardHolder()); //   开户名
        legalPerson.put("bankCardPhone", bizMerchantInfo.getBankCardPhone()); //  银行卡预留手机号
        legalPerson.put("bankCardPic", bizMerchantInfo.getBankCardPic()); //  银行卡照片
        legalPerson.put("bankCity", bizMerchantInfo.getBankCity()); //  开户银行城市
        legalPerson.put("bankCode", bizMerchantInfo.getBankCode()); //  银行编码
        legalPerson.put("bankProvince", bizMerchantInfo.getBankProvince()); //  开户银行省份
        legalPerson.put("bankSite", bizMerchantInfo.getBankSite()); //  开户行网点
        legalPerson.put("unionpayCode", bizMerchantInfo.getUnionpayCode()); //  开户支行联行号
        //  settleAccountInfo.put("bankCardAccountType", Byte.decode("1")); //  结算账户类型2：企业1：个人
        JSONObject userRegistrationInfo = new JSONObject();
        legalPerson.put("phone", bizMerchantInfo.getPhone()); //  注册手机
        //  userRegistrationInfo.put("registerTime", DateUtils.dateFormatString(new Date())); //  注册时间（例："2019-09-09 20:00:00"）（调用修改时不需要传入该字段
        String userName = IdWorker.getIdStr();
        legalPerson.put("userName", userName); //  用户名（1、唯一；每次请求都要换一个新的，因为涉及到其他部门接口，不是一个事务内2、用uuid即可）（调用修改时不需要传入该字段）
        JSONObject locationInfoDto = new JSONObject();
        legalPerson.put("activeAddress", bizMerchantInfo.getActiveAddress()); //  商户活体检测地址
        legalPerson.put("activeLatitude", bizMerchantInfo.getActiveLatitude()); //  	商户活体检测地址纬度
        legalPerson.put("activeLongitude", bizMerchantInfo.getActiveLongitude()); //  	商户活体检测地址经度
        legalPerson.put("registerAddress", bizMerchantInfo.getRegisterAddress()); //  商户注册地址
        legalPerson.put("registerLatitude", bizMerchantInfo.getRegisterLatitude()); //  商户注册地址纬度
        legalPerson.put("registerLongitude", bizMerchantInfo.getRegisterLongitude()); //  商户注册地址经度
        //乐刷2024-01-18 新增
        legalPerson.put("shopInsidePlacePic", bizMerchantInfo.getShopInsidePlacePic()); //  商户注册地址经度
        legalPerson.put("shopGatePic", bizMerchantInfo.getShopGatePic()); //  商户注册地址经度
        legalPerson.put("cashierDeskPic", bizMerchantInfo.getCashierDeskPic()); //  商户注册地址经度
        legalPerson.put("agentid", "ANXINFU");
        legalPerson.put("posCode", bizMerchantInfo.getPosCode());
        legalPerson.put("feeId", bizMerchantInfo.getFeeId());

        //乐刷个体新增
        legalPerson.put("businessLicenseNo",bizMerchantInfo.getBusinessLicenseNo());
        legalPerson.put("businessLicenseName",bizMerchantInfo.getBusinessLicenseName());
        legalPerson.put("businessLicenseStartDate",bizMerchantInfo.getBusinessLicenseStartDate());
        legalPerson.put("businessLicenseEndDate",bizMerchantInfo.getBusinessLicenseEndDate());
        legalPerson.put("businessCreditLicensePic",bizMerchantInfo.getBusinessCreditLicensePic());
        legalPerson.put("businessLicenseType",bizMerchantInfo.getBusinessLicenseType());
        legalPerson.put("bankCardAccountType",bizMerchantInfo.getBankCardAccountType());
        legalPerson.put("merchantType",bizMerchantInfo.getMerchantType());
        legalPerson.put("bankCardBackPic",bizMerchantInfo.getBankCardBackPic());
        System.out.println("请求参数--》》》》" + JSONObject.toJSONString(legalPerson));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getMerchantsInfo(), JSONObject.toJSONString(legalPerson));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        JSONObject data = jsonObject.getJSONObject("data");
        String desc="";
        if(data!=null){
            desc = data.getString("desc");
        }else{
            desc=msg;
        }
        jsonObject.put("uuid",userName);
        if (code.equals("200")) {  //成功
            String merchantId = data.getString("merchantId");
            String merchantNo = data.getString("merchantNo");
            System.out.println("POSP商户审核成功"+bizMerchantInfo.getLegalPersonName());
            System.out.println("POSP商户标号"+merchantNo);
            String sn = data.getString("sn");
            bizMerchantInfo.setMerchantId(merchantId);
            if (data.getBoolean("infoCompleted")) {
                bizMerchantInfo.setInfoCompleted("0");
            } else {
                bizMerchantInfo.setInfoCompleted("1");
            }
            bizMerchantInfo.setMerchantKey(data.getString("merchantKey"));
            bizMerchantInfo.setMasterKeys(data.getString("masterkeys"));
            bizMerchantInfo.setValidationValue(data.getString("validationValue"));
            bizMerchantInfo.setAuditStatus("2");
            bizMerchantInfo.setSn(sn);
            bizMerchantInfo.setMerchId(posMachineBySnCode.getMerchId());
            bizMerchantInfo.setMerchantDesc(desc);
            bizMerchantInfo.setMerchantCode(merchantNo);
            bizMerchantInfo.setCertificateType("1");
            bizMerchantInfo.setProductType("POS");
            bizMerchantInfo.setMccCode("4812");
            bizMerchantInfo.setMerchantSubType("4");
            bizMerchantInfo.setMerchantType("1");
            bizMerchantInfo.setBankCardAccountType("1");
            bizMerchantInfo.setUserName(userName);
            bizMerchantInfo.setMerchantLevel(data.getString("merchantLevel"));
            bizMerchantInfo.setRegisterTime(DateUtils.dateFormatString(new Date()));
            bizMerchantInfo.setClientServicePhoneNo(bizMerchantInfo.getBankCardPhone());
            bizMerchantInfo.setMerchantName(bizMerchantInfo.getLegalPersonName());
            if(StringUtils.isBlank(bizMerchantInfo.getApplicant())){
                bizMerchantInfo.setApplicant(bizMerchantInfo.getLegalPersonName());
            }
            bizMerchantInfo.setRegisterAddress(bizMerchantInfo.getActiveAddress());
            bizMerchantInfo.setRegisterLatitude(bizMerchantInfo.getActiveLatitude());
            bizMerchantInfo.setRegisterLongitude(bizMerchantInfo.getActiveLongitude());
          //  bizMerchantInfoMapper.insertBizEntrySn(bizMerchantInfo);
            try{
                BizChannel  bizChannel = bizMerchantInfoService.getChannelDataByChannel(posMachineBySnCode.getChannel());
                bizMerchantInfo.setChannelName(bizChannel.getChannelName());
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
            //存到自己的库里
            boolean save = bizMerchantInfoService.save(bizMerchantInfo);
            //推送审核成功消息
            String fanXianMess = "SN：" + bizMerchantInfo.getPosCode() + "审核成功";
            BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
            fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
            fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
            fanXianMessageRecords.setReadStatus(0); // 消息未读
            fanXianMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
            return jsonObject;
        } else {
            //推送审核成功消息
            String fanXianMess = "SN：" + bizMerchantInfo.getPosCode() + "审核失败"+desc;
            BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
            fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
            fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
            fanXianMessageRecords.setReadStatus(0); // 消息未读
            fanXianMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", msg);
            return erro;
        }

    }

    @Override
    public JSONObject updateMerchantsInfo(BizMerchantInfo merchantInfo) {
        JSONObject legalPerson = new JSONObject();
        //修改
        if ("".equals(merchantInfo.getMerchantCode()) && merchantInfo.getMerchantCode() == null) {
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "商户编号不能为空");
            return erro;
        }
        BizMerchantInfo bizMerchantInfo = bizMerchantInfoService.getMerchantInfo(merchantInfo);
        bizMerchantInfo.setFeeId(merchantInfo.getFeeId());  //  费率id
        bizMerchantInfo.setBankCardPic(merchantInfo.getBankCardPic()); // 银行卡照片
        bizMerchantInfo.setBankCardAccount(merchantInfo.getBankCardAccount()); //银行卡号
        bizMerchantInfo.setBankCardHolder(merchantInfo.getBankCardHolder()); // 开户名
        bizMerchantInfo.setBankCardPhone(merchantInfo.getBankCardPhone()); // 预留手机好
        bizMerchantInfo.setProvinceNo(merchantInfo.getProvinceNo()); // 开户省
        bizMerchantInfo.setCityNo(merchantInfo.getCityNo()); // 开户市
        bizMerchantInfo.setAreaNo(merchantInfo.getAreaNo()); // 开户区
        bizMerchantInfo.setBankCode(merchantInfo.getBankCode()); // 银行编码
        bizMerchantInfo.setBankSite(merchantInfo.getBankSite()); // 网点
        legalPerson.put("merchantCode", bizMerchantInfo.getMerchantCode());
        legalPerson.put("certificateEndDate", bizMerchantInfo.getCertificateEndDate()); //  证件有效期截止日期（例：1949-10-01）;
        legalPerson.put("certificateNo", bizMerchantInfo.getCertificateNo());   //  法人证件号码
        legalPerson.put("certificateStartDate", bizMerchantInfo.getCertificateStartDate()); //  证件有效期开始日期（例：1949-10-01）
        legalPerson.put("certificatesBackPic", bizMerchantInfo.getCertificatesBackPic()); //  证件国徽面
        legalPerson.put("certificatesFrontPic", bizMerchantInfo.getCertificatesFrontPic()); //  证件人脸面
        legalPerson.put("idcardHandPic", bizMerchantInfo.getIdcardHandPic()); //  手持身份证照片（与法人人脸识别留存照片两者必须有一个不为空）; 例如:picture2/手持身份证照片.jpg
        legalPerson.put("legalPersonName", bizMerchantInfo.getLegalPersonName()); //  法人姓名
        legalPerson.put("address", bizMerchantInfo.getAddress()); //  详细地址
        legalPerson.put("posCode", bizMerchantInfo.getPosCode()); //  详细地址
        //通用一个人
        legalPerson.put("applicant", bizMerchantInfo.getLegalPersonName()); //  联系人（固定为法人名称
        legalPerson.put("areaNo", bizMerchantInfo.getAreaNo()); //  区县代码
        legalPerson.put("cityNo", bizMerchantInfo.getCityNo()); //   城市编号
        legalPerson.put("clientServicePhoneNo", bizMerchantInfo.getClientServicePhoneNo()); //   客服电话
        legalPerson.put("contactPhoneNo", bizMerchantInfo.getContactPhoneNo()); //  联系电话
        legalPerson.put("merchantName", bizMerchantInfo.getLegalPersonName()); //  商户名称（固定格式：前缀”商户_“+法人名称）
        legalPerson.put("merchantShortHand", bizMerchantInfo.getMerchantShortHand()); //  商户简写
        legalPerson.put("provinceNo", bizMerchantInfo.getProvinceNo()); //  省份代码（调用修改时不需要传入该字段）
        JSONObject settleAccountInfo = new JSONObject();
        legalPerson.put("bankCardAccount", bizMerchantInfo.getBankCardAccount()); //  银行账号
        legalPerson.put("bankCardHolder", bizMerchantInfo.getBankCardHolder()); //   开户名
        legalPerson.put("bankCardPhone", bizMerchantInfo.getBankCardPhone()); //  银行卡预留手机号
        legalPerson.put("bankCardPic", bizMerchantInfo.getBankCardPic()); //  银行卡照片
        legalPerson.put("bankCity", bizMerchantInfo.getBankCity()); //  开户银行城市
        legalPerson.put("bankCode", bizMerchantInfo.getBankCode()); //  银行编码
        legalPerson.put("bankProvince", bizMerchantInfo.getBankProvince()); //  开户银行省份
        legalPerson.put("bankSite", bizMerchantInfo.getBankSite()); //  开户行网点
        legalPerson.put("unionpayCode", bizMerchantInfo.getUnionpayCode()); //  开户支行联行号
        legalPerson.put("phone", bizMerchantInfo.getPhone()); //  注册手机
        String userName = IdWorker.getIdStr();
        legalPerson.put("userName", userName); //  用户名（1、唯一；每次请求都要换一个新的，因为涉及到其他部门接口，不是一个事务内2、用uuid即可）（调用修改时不需要传入该字段）
        legalPerson.put("activeAddress", bizMerchantInfo.getActiveAddress()); //  商户活体检测地址
        legalPerson.put("activeLatitude", bizMerchantInfo.getActiveLatitude()); //  	商户活体检测地址纬度
        legalPerson.put("activeLongitude", bizMerchantInfo.getActiveLongitude()); //  	商户活体检测地址经度
        legalPerson.put("registerAddress", bizMerchantInfo.getRegisterAddress()); //  商户注册地址
        legalPerson.put("registerLatitude", bizMerchantInfo.getRegisterLatitude()); //  商户注册地址纬度
        legalPerson.put("registerLongitude", bizMerchantInfo.getRegisterLongitude()); //  商户注册地址经度
        legalPerson.put("agentid", this.agentid());
        legalPerson.put("feeId", bizMerchantInfo.getFeeId());
        //乐刷个体新增
        legalPerson.put("businessLicenseNo",bizMerchantInfo.getBusinessLicenseNo());
        legalPerson.put("businessLicenseName",bizMerchantInfo.getBusinessLicenseName());
        legalPerson.put("businessLicenseStartDate",bizMerchantInfo.getBusinessLicenseStartDate());
        legalPerson.put("businessLicenseEndDate",bizMerchantInfo.getBusinessLicenseEndDate());
        legalPerson.put("businessCreditLicensePic",bizMerchantInfo.getBusinessCreditLicensePic());
        legalPerson.put("businessLicenseType",bizMerchantInfo.getBusinessLicenseType());
        legalPerson.put("bankCardAccountType",bizMerchantInfo.getBankCardAccountType());
        legalPerson.put("merchantType",bizMerchantInfo.getMerchantType());
        legalPerson.put("bankCardBackPic",bizMerchantInfo.getBankCardBackPic());
        System.out.println("请求参数--》》》》" + JSONObject.toJSONString(legalPerson));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getMerchantsInfo(), JSONObject.toJSONString(legalPerson));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if (code.equals("200")) {  //成功
            JSONObject data = jsonObject.getJSONObject("data");
            String desc = data.getString("desc");
            bizMerchantInfo.setMerchantDesc(desc);
            bizMerchantInfo.setUpdateTime(new Date());
            bizMerchantInfo.setUpdateResult(data.getString("updateResult"));
            bizMerchantInfo.setAuditStatus("2");
            //更新自己的库
            bizMerchantInfoService.updateMerchantsInfoByMerchantCode(bizMerchantInfo);
            return jsonObject;
        } else {
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "操作失败");
            return erro;
        }
    }

    @Override
    @Transactional
    public JSONObject updateAllMerchantsInfo(BizMerchantInfo bizMerchantInfo) {
        JSONObject legalPerson = new JSONObject();
        if ("".equals(bizMerchantInfo.getMerchantCode()) && bizMerchantInfo.getMerchantCode() == null) {
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "商户编号不能为空");
            return erro;
        }
        String merchantCode = bizMerchantInfo.getMerchantCode();
        BizPosMachine posMachineBySnCode = posMachineService.getPosMachineBySnCode(bizMerchantInfo.getPosCode());
        if(posMachineBySnCode == null){
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "设备不存在");
            return  erro;
        }
        // 代理
        BizMerchant merchantByMerchId = bizMerchantService.getMerchantByMerchId(posMachineBySnCode.getMerchId());

        //报件id
        BizMerchantInfo bizMerchantInfo1 = bizMerchantInfoService.getMerchantInfo(bizMerchantInfo);
//        BizMerchantInfo bizMerchantInfo1 =  bizMerchantInfoMapper.selectMerchantInfoByCertificateNoAndSn(bizMerchantInfo);
//        if (bizMerchantInfo1 != null){ //删除进件失败的
//            bizMerchantInfoMapper.deleteMerchantInfoById(bizMerchantInfo1.getId());
//        }
        String certificateEndDate="";
        if(bizMerchantInfo.getCertificateEndDate().equals("长期")){
            certificateEndDate=bizMerchantInfo.getCertificateEndDate();
        }else{
            certificateEndDate=bizMerchantInfo.getCertificateEndDate().replace(".","");
            certificateEndDate=certificateEndDate.replaceAll("-","");
            certificateEndDate=certificateEndDate.replace("年","");
            certificateEndDate=certificateEndDate.replace("月","");
            certificateEndDate=certificateEndDate.replace("日","");
            certificateEndDate=DateUtils.dateConvertion(certificateEndDate);
        }

        String certificateStartDate=bizMerchantInfo.getCertificateStartDate().replace(".","");
        certificateStartDate=certificateStartDate.replaceAll("-","");
        certificateStartDate=certificateStartDate.replace("年","");
        certificateStartDate=certificateStartDate.replace("月","");
        certificateStartDate=certificateStartDate.replace("日","");
        certificateStartDate=DateUtils.dateConvertion(certificateStartDate);
        legalPerson.put("certificateEndDate", certificateEndDate); //  证件有效期截止日期（例：1949-10-01）;
        legalPerson.put("certificateNo", bizMerchantInfo.getCertificateNo());   //  法人证件号码
        legalPerson.put("certificateStartDate", certificateStartDate); //  证件有效期开始日期（例：1949-10-01）
        //暂时写死
        //  legalPerson.put("certificateType", Byte.decode("1")); //  法人证件类型,1：身份证,2：港澳通行证,3：台湾身份证,4：HK身份证,5：MC身份证,6：护照,7：居住证,9：其他法定证件（如提供身份证以外资料，进件时将转人工审核）（调用修改时不需要传入该字段）
        legalPerson.put("certificatesBackPic", bizMerchantInfo.getCertificatesBackPic()); //  证件国徽面
        legalPerson.put("certificatesFrontPic", bizMerchantInfo.getCertificatesFrontPic()); //  证件人脸面
        legalPerson.put("idcardHandPic", bizMerchantInfo.getIdcardHandPic()); //  手持身份证照片（与法人人脸识别留存照片两者必须有一个不为空）; 例如:picture2/手持身份证照片.jpg
        legalPerson.put("legalPersonName", bizMerchantInfo.getLegalPersonName()); //  法人姓名
        JSONObject merchantInfo = new JSONObject();
        //转成数组
        List<String> productType = new ArrayList<>();
        //暂时写死
        //  productType.add("POS");
        legalPerson.put("address", bizMerchantInfo.getAddress()); //  详细地址
        //通用一个人
        legalPerson.put("applicant", bizMerchantInfo.getLegalPersonName()); //  联系人（固定为法人名称
        legalPerson.put("areaNo", bizMerchantInfo.getAreaNo()); //  区县代码
        legalPerson.put("cityNo", bizMerchantInfo.getCityNo()); //   城市编号
        legalPerson.put("provinceName", bizMerchantInfo.getProvinceName()); //   城市编号
        legalPerson.put("cityName", bizMerchantInfo.getCityName()); //   城市编号
        legalPerson.put("areaName", bizMerchantInfo.getAreaName()); //   城市编号
        legalPerson.put("clientServicePhoneNo", bizMerchantInfo.getClientServicePhoneNo()); //   客服电话
        legalPerson.put("contactPhoneNo", bizMerchantInfo.getContactPhoneNo()); //  联系电话
        // mcc码暂时先这么写  mcc = 4812
        // merchantInfo.put("mccCode", "4812"); //  所属行业mcc码
        legalPerson.put("merchantName", bizMerchantInfo.getLegalPersonName()); //  商户名称（固定格式：前缀”商户_“+法人名称）
        if(null!=posMachineBySnCode.getChannel()&&!"".equals(posMachineBySnCode.getChannel())){
            if(posMachineBySnCode.getChannel().equals("1")){
                if(bizMerchantInfo.getMcc() == null || "".equals(bizMerchantInfo.getMcc())){
                    JSONObject erro = new JSONObject();
                    erro.put("code", 500);
                    erro.put("msg", "请选择行业");
                    return erro;
                }
//                BizPosLsMcc mccVo=bizMerchantInfoMapper.getlsIndustry(bizMerchantInfo.getMcc());
                legalPerson.put("merchantShortHand", bizMerchantInfo.getMerchantShortHand()); //  商户简写
                legalPerson.put("mccCode",bizMerchantInfo.getMcc());
            }else{
                legalPerson.put("merchantShortHand", bizMerchantInfo.getMerchantShortHand()); //  商户简写
            }
        }
        //暂时写死
        // merchantInfo.put("merchantSubType", "4"); //  商户子类型：1：小微A;2：小微B;3：小微C;4：小微D
        //暂时写死了
        //  merchantInfo.put("merchantType", Byte.decode("1")); //  商户类型,1：个人,2：个体,3：企业(调用修改时不需要传入该字段）
        //  merchantInfo.put("productType", productType); //  array	申请产品类型;例["SHOUSHUA","POS"] 具体类型：POS,SAOMA,SHOUSHUA
        legalPerson.put("provinceNo", bizMerchantInfo.getProvinceNo()); //  省份代码（调用修改时不需要传入该字段）
        JSONObject settleAccountInfo = new JSONObject();
        legalPerson.put("bankCardAccount", bizMerchantInfo.getBankCardAccount()); //  银行账号
        legalPerson.put("bankCardHolder", bizMerchantInfo.getBankCardHolder()); //   开户名
        legalPerson.put("bankCardPhone", bizMerchantInfo.getBankCardPhone()); //  银行卡预留手机号
        legalPerson.put("bankCardPic", bizMerchantInfo.getBankCardPic()); //  银行卡照片
        legalPerson.put("bankCity", bizMerchantInfo.getBankCity()); //  开户银行城市
        legalPerson.put("bankCode", bizMerchantInfo.getBankCode()); //  银行编码
        legalPerson.put("bankProvince", bizMerchantInfo.getBankProvince()); //  开户银行省份
        legalPerson.put("bankSite", bizMerchantInfo.getBankSite()); //  开户行网点
        legalPerson.put("unionpayCode", bizMerchantInfo.getUnionpayCode()); //  开户支行联行号
        //  settleAccountInfo.put("bankCardAccountType", Byte.decode("1")); //  结算账户类型2：企业1：个人
        JSONObject userRegistrationInfo = new JSONObject();
        legalPerson.put("phone", bizMerchantInfo.getPhone()); //  注册手机
        //  userRegistrationInfo.put("registerTime", DateUtils.dateFormatString(new Date())); //  注册时间（例："2019-09-09 20:00:00"）（调用修改时不需要传入该字段
        String userName = IdWorker.getIdStr();
        legalPerson.put("userName", userName); //  用户名（1、唯一；每次请求都要换一个新的，因为涉及到其他部门接口，不是一个事务内2、用uuid即可）（调用修改时不需要传入该字段）
        JSONObject locationInfoDto = new JSONObject();
        legalPerson.put("activeAddress", bizMerchantInfo.getActiveAddress()); //  商户活体检测地址
        legalPerson.put("activeLatitude", bizMerchantInfo.getActiveLatitude()); //  	商户活体检测地址纬度
        legalPerson.put("activeLongitude", bizMerchantInfo.getActiveLongitude()); //  	商户活体检测地址经度
        legalPerson.put("registerAddress", bizMerchantInfo.getRegisterAddress()); //  商户注册地址
        legalPerson.put("registerLatitude", bizMerchantInfo.getRegisterLatitude()); //  商户注册地址纬度
        legalPerson.put("registerLongitude", bizMerchantInfo.getRegisterLongitude()); //  商户注册地址经度
        String img=bizMerchantInfo.getImg();
        if(null!=img)
            legalPerson.put("qbFaceRecognition", img.substring(img.indexOf(",")+1)); //  图片bas64
        legalPerson.put("agentid", "ANXINFU");
        legalPerson.put("posCode", bizMerchantInfo.getPosCode());
        legalPerson.put("feeId", bizMerchantInfo.getFeeId());
        legalPerson.put("merchantCode", bizMerchantInfo.getMerchantCode());
        //企业进件20240116新增
        legalPerson.put("settAccMark", bizMerchantInfo.getSettAccMark());
        legalPerson.put("busNature", bizMerchantInfo.getBusNature());
        legalPerson.put("busRegNo", bizMerchantInfo.getBusRegNo());
        legalPerson.put("busRegType", bizMerchantInfo.getBusRegType());
        legalPerson.put("receiptProImg", bizMerchantInfo.getReceiptProImg());
        legalPerson.put("busiLicenseImg", bizMerchantInfo.getBusiLicenseImg());
        legalPerson.put("cashDeskImg", bizMerchantInfo.getCashDeskImg());
        legalPerson.put("busiPlaceImg", bizMerchantInfo.getBusiPlaceImg());
        legalPerson.put("busiDoorImg", bizMerchantInfo.getBusiDoorImg());
        legalPerson.put("bankAboveImg", bizMerchantInfo.getBankAboveImg());
        legalPerson.put("settleProImg", bizMerchantInfo.getSettleProImg());
        legalPerson.put("otherImg1", bizMerchantInfo.getOtherImg1());
        legalPerson.put("busRegStartDt", bizMerchantInfo.getBusRegStartDt());
        legalPerson.put("busRegEndDt", bizMerchantInfo.getBusRegEndDt());
        legalPerson.put("legalpersonIsSett", bizMerchantInfo.getLegalpersonIsSett());
        legalPerson.put("settCrpNo", bizMerchantInfo.getSettCrpNo());
        legalPerson.put("settCrpAboveImg", bizMerchantInfo.getSettCrpAboveImg());
        legalPerson.put("settCrpBelovImg", bizMerchantInfo.getSettCrpBelovImg());
        legalPerson.put("nonCrpNmSettleProImg", bizMerchantInfo.getNonCrpNmSettleProImg());
        legalPerson.put("mercTypeMCC", bizMerchantInfo.getMccCd());
        //乐刷新增2024-01-18
        legalPerson.put("shopInsidePlacePic", bizMerchantInfo.getShopInsidePlacePic());
        legalPerson.put("shopGatePic", bizMerchantInfo.getShopGatePic());
        legalPerson.put("cashierDeskPic", bizMerchantInfo.getCashierDeskPic());
        legalPerson.put("bankName", bizMerchantInfo.getBankName());

        //乐刷个体新增
        legalPerson.put("businessLicenseNo",bizMerchantInfo.getBusinessLicenseNo());
        legalPerson.put("businessLicenseName",bizMerchantInfo.getBusinessLicenseName());
        legalPerson.put("businessLicenseStartDate",bizMerchantInfo.getBusinessLicenseStartDate());
        legalPerson.put("businessLicenseEndDate",bizMerchantInfo.getBusinessLicenseEndDate());
        legalPerson.put("businessCreditLicensePic",bizMerchantInfo.getBusinessCreditLicensePic());
        legalPerson.put("businessLicenseType",bizMerchantInfo.getBusinessLicenseType());
        legalPerson.put("bankCardAccountType",bizMerchantInfo.getBankCardAccountType());
        legalPerson.put("merchantType",bizMerchantInfo.getMerchantType());
        legalPerson.put("bankCardBackPic",bizMerchantInfo.getBankCardBackPic());
        System.out.println("请求参数--》》》》" + JSONObject.toJSONString(legalPerson));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getUpdateAllMerchantInfo(), JSONObject.toJSONString(legalPerson));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        JSONObject data = jsonObject.getJSONObject("data");
        String desc="";
        if(data!=null){
            desc = data.getString("desc");
        }else{
            desc=msg;
        }
        if (code.equals("200")) {  //成功
            if(null!=data){
                String merchantId = data.getString("merchantId");
                String merchantNo = data.getString("merchantNo");
                System.out.println("POSP商户标号"+merchantNo);
                bizMerchantInfo.setMerchantId(merchantId);
                if (data.getBoolean("infoCompleted")) {
                    bizMerchantInfo.setInfoCompleted("0");
                } else {
                    bizMerchantInfo.setInfoCompleted("1");
                }
                bizMerchantInfo.setMerchantCode(merchantNo);
                bizMerchantInfo.setMerchantLevel(data.getString("merchantLevel"));
                String sn = data.getString("sn");
                bizMerchantInfo.setSn(sn);
                bizMerchantInfo.setMerchantKey(data.getString("merchantKey"));
                bizMerchantInfo.setMasterKeys(data.getString("masterkeys"));
                bizMerchantInfo.setValidationValue(data.getString("validationValue"));
            }
            System.out.println("POSP商户审核成功"+bizMerchantInfo.getLegalPersonName());
            bizMerchantInfo.setAuditStatus("2");
            bizMerchantInfo.setMerchId(posMachineBySnCode.getMerchId());
            bizMerchantInfo.setMerchantDesc(desc);
            bizMerchantInfo.setCertificateType("1");
            bizMerchantInfo.setProductType("POS");
            bizMerchantInfo.setMccCode("4812");
            bizMerchantInfo.setMerchantSubType("4");
            bizMerchantInfo.setMerchantType("1");
            bizMerchantInfo.setBankCardAccountType("1");
            bizMerchantInfo.setUserName(userName);
            bizMerchantInfo.setRegisterTime(DateUtils.dateFormatString(new Date()));
            bizMerchantInfo.setClientServicePhoneNo(bizMerchantInfo.getBankCardPhone());
            bizMerchantInfo.setMerchantName(bizMerchantInfo.getLegalPersonName());
            bizMerchantInfo.setRegisterAddress(bizMerchantInfo.getActiveAddress());
            bizMerchantInfo.setRegisterLatitude(bizMerchantInfo.getActiveLatitude());
            bizMerchantInfo.setRegisterLongitude(bizMerchantInfo.getActiveLongitude());
            bizMerchantInfo.setMerchantCode(merchantCode);

            bizMerchantInfo.setId(bizMerchantInfo1.getId());
            //  bizMerchantInfoMapper.insertBizEntrySn(bizMerchantInfo);
            //存到自己的库里
            boolean save = bizMerchantInfoService.saveOrUpdate(bizMerchantInfo);
            //推送审核成功消息
            String fanXianMess = "SN：" + bizMerchantInfo.getPosCode() + "审核成功";
            BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
            fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
            fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
            fanXianMessageRecords.setReadStatus(0); // 消息未读
            fanXianMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
//            //绑定无押设备
//            if (com.cykj.common.utils.StringUtils.isNotEmpty(posMachineBySnCode.getVar5())&&!"0".equals(posMachineBySnCode.getVar5())){ //有押
//                    //有押的不管
//            }else { // 无押 调取绑定
//                BindPosDto bindPosDto = new BindPosDto();
//                bindPosDto.setPosCode(posMachineBySnCode.getPosCode());
//                bindPosDto.setMerchantNo(merchantNo);
//                AjaxResult ajaxResult1 = bindingPosCode(bindPosDto);
//                if("0".equals(ajaxResult1.get("type"))){
//                    //绑定成功
//                    jsonObject.put("type","0");
//                    System.out.println("绑定成功posCode: "+posMachineBySnCode.getPosCode()+" merchantNo  "+ merchantNo +"绑定结果 "+  ajaxResult1.get("type"));
//                }else{
//                    //绑定失败
//                    System.out.println("绑定失败posCode: "+posMachineBySnCode.getPosCode()+" merchantNo  "+ merchantNo +"绑定结果 "+  ajaxResult1.get("type"));
//                    jsonObject.put("type","1");
//                }
//            }
            return jsonObject;
        } else {

            //推送审核成功消息
            String fanXianMess = "SN：" + bizMerchantInfo.getPosCode() + "审核失败"+desc;
            BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
            fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
            fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
            fanXianMessageRecords.setReadStatus(0); // 消息未读
            fanXianMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", msg);
            return erro;
        }

    }
    @Override
    public List<BizMercahntFeeNameDTO> echoFeeId() {
        return bizMerchantInfoMapper.echoFeeId();
    }

    @Override
    public BizMerchantDTO echoMerchantInfo(BizMerchantInfo bizMerchantInfo) {
     //   return bizMerchantInfoMapper.echoMerchantInfo(bizMerchantInfo);
        return bizMerchantInfoMapper.echoMerchantInfoNewFee(bizMerchantInfo);
    }

    @Override
    public void updateMerchantsInfoByMerchantCode(BizMerchantInfo bizMerchantInfo) {
        bizMerchantInfoMapper.updateMerchantsInfoByMerchantCode(bizMerchantInfo);
    }

    @Override
    public int queryMyMerchNum(Long userId) {
        BizMerchant bizMerchant = bizMerchantService.getMerchantByUserId(userId);
        int num = bizMerchantInfoMapper.selectNumPOSP(bizMerchant.getMerchId());
        return num;
    }


    @Override
    public List<BizMerchantInfo> selectMerchantInfoByAuditStatus() {
        List<BizMerchantInfo> list = bizMerchantInfoMapper.selectMerchantInfoByAuditStatus();
        return list;
    }



    @Override
    public int updateByMerchantCode(BizMerchantInfo bizMerchantInfo) {
        BizMerchantInfo merchantInfo = bizMerchantInfoMapper.getMerchantInfo(bizMerchantInfo);
        if ("0".equals(bizMerchantInfo.getAuditStatus())){ // 待审核
            bizMerchantInfo.setAuditStatus("2");
        }else if ("-2".equals(bizMerchantInfo.getAuditStatus())){  // 失败
            bizMerchantInfo.setAuditStatus("1");
        }else if ("-1".equals(bizMerchantInfo.getAuditStatus())){  // 失败
            bizMerchantInfo.setAuditStatus("1");
        }else if("3".equals(bizMerchantInfo.getAuditStatus())){ // 成功
            BizPosMachine posMachineBySnCode = posMachineService.getPosMachineBySnCode(merchantInfo.getPosCode());
            if(posMachineBySnCode != null){
                //绑定无押设备
                if (com.cykj.common.utils.StringUtils.isNotEmpty(posMachineBySnCode.getVar5())&&!"0".equals(posMachineBySnCode.getVar5())){ //有押
                    //有押的不管
                }else { // 无押 调取绑定
                    BindPosDto bindPosDto = new BindPosDto();
                    bindPosDto.setPosCode(posMachineBySnCode.getPosCode());
                    bindPosDto.setMerchantNo(bizMerchantInfo.getMerchantCode());
                    AjaxResult ajaxResult1 = bindingPosCode(bindPosDto);
                    if("0".equals(ajaxResult1.get("type"))){
                        //绑定成功
                        System.out.println("绑定成功posCode: "+posMachineBySnCode.getPosCode()+" merchantNo  "+ bizMerchantInfo.getMerchantCode() +"绑定结果 "+  ajaxResult1.get("type"));
                    }else{
                        //绑定失败
                        System.out.println("绑定失败posCode: "+posMachineBySnCode.getPosCode()+" merchantNo  "+ bizMerchantInfo.getMerchantCode() +"绑定结果 "+  ajaxResult1.get("type"));
                    }
                }
            }
        }
        return bizMerchantInfoMapper.updateByMerchantCode(bizMerchantInfo);
    }

    @Override
    public void updateFeeIdByMerchantNo(String merchantCode, Long feeId) {
        bizMerchantInfoMapper.updateFeeIdByMerchantNo(merchantCode, feeId);
    }

    @Override
    public AjaxResult bindingPosCode(BindPosDto bindPosDto) {
        //查看设备是否有押  创建押金代扣   无不创建    创建流量
        AjaxResult ajaxResult = AjaxResult.success();
        BizPosMachine posMachineBySnCode = posMachineService.getPosMachineBySnCode(bindPosDto.getPosCode());
        if (posMachineBySnCode == null) {
            return AjaxResult.error("无此设备");
        }
        JSONObject param = new JSONObject();
        String posType = posMachineBySnCode.getPosType();
        String type = "0";
        if (posType.equals("6")) {
            param.put("posType", "1");  //1有押
        } else {
            param.put("posType", "2");   // 2无押
        }
        param.put("merchantNo", bindPosDto.getMerchantNo());
        param.put("posCode", bindPosDto.getPosCode());
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getBindingPosCode(), JSONObject.toJSONString(param));
        JSONObject paramObject = JSONObject.parseObject(result);
        if (paramObject.getInteger("code") == 200) {
            posMachineService.updatePosPosMachineActivateStatusBySn(bindPosDto.getPosCode());
            bizMerchantInfoMapper.updateMercahntInfoWhetherBinding(bindPosDto.getMerchantNo(),bindPosDto.getPosCode());
//
//            BizMerchantInfo Info =new BizMerchantInfo();
//            Info.setMerchantCode(bindPosDto.getMerchantNo());
//            BizMerchantInfo bizMerchantInfo = bizMerchantInfoMapper.getMerchantInfo(Info);
//            BizPosMachine bizPosMachine = posMachineService.selectPosBySnCode(bindPosDto.getPosCode());
//            BizMerchantEntry bizMerchantEntry = new BizMerchantEntry();
//            bizMerchantEntry.setSn(bizMerchantInfo.getPosCode()); //sn
//            bizMerchantEntry.setCertificateno(bizMerchantInfo.getCertificateNo()); //身份证号
//            bizMerchantEntry.setPhone(bizMerchantInfo.getBankCardPhone());  // 预留手机号
//            bizMerchantEntry.setApplicant(bizMerchantInfo.getLegalPersonName()); // 姓名
//            bizMerchantEntry.setMerchantNo(bizMerchantInfo.getMerchantCode()); // 姓名
//            bizMerchantEntry.setTerminalCode(bizPosMachine.getPosType()); // 姓名
            //激活表插入数据
//            int ok = recordsService.snRecordsOneVersion(bizMerchantEntry);
            //更新设备表绑定状态
//            System.out.println("绑定成功"+bindPosDto.getPosCode()+DateUtils.dateFormatString(new Date()));
//            // 插入 新绑定激活表
//            PosBindActiveRecords posBindActiveRecords = new PosBindActiveRecords();
//            posBindActiveRecords.setMerchId(posMachineBySnCode.getMerchId());
//            BizMerchant bizMerchant = bizMerchantService.getMerchantByMerchId(posMachineBySnCode.getMerchId());
//            posBindActiveRecords.setMerchantName(bizMerchant.getMerchName());
//            posBindActiveRecords.setMerchantCode(bindPosDto.getMerchantNo());
//            posBindActiveRecords.setMerchantName(bizMerchantInfoMapper.getInfoByMerchantCode(bindPosDto.getMerchantNo()).getLegalPersonName());
//            posBindActiveRecords.setPosSn(bindPosDto.getPosCode());
//            posBindActiveRecords.setBindTime(new Date());
//            iPosBindActiveRecordsService.saveOrUpdate(posBindActiveRecords);
            //新增激活表信息
            BizPosMachineStatusRecords bizPosMachineStatusRecords=new BizPosMachineStatusRecords();
            bizPosMachineStatusRecords.setSnCode(bindPosDto.getPosCode());
            bizPosMachineStatusRecords.setMerchantId(bindPosDto.getMerchantNo());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            bizPosMachineStatusRecords.setTime(sdf.format(new Date()));
            BizMerchantInfo bizMerchantInfo = bizMerchantInfoMapper.getMerchantInfoByMerchantCode(bindPosDto.getMerchantNo());
            bizPosMachineStatusRecords.setName(bizMerchantInfo.getLegalPersonName());
            bizPosMachineStatusRecords.setPhoneNo(bizMerchantInfo.getContactPhoneNo());
            bizPosMachineStatusRecordsMapper.insertBizPosMachineStatusRecords(bizPosMachineStatusRecords);
            ajaxResult.put("type", type);
            return ajaxResult;
        } else {
            return AjaxResult.error(paramObject.getString("msg"));
        }
    }

    @Override
    public AjaxResult wishCheckPartnerPhotoUpload(BindPosDto bindPosDto) {
        JSONObject param = new JSONObject();
        param.put("photo", bindPosDto.getPhoto());
        param.put("merchantNo", bindPosDto.getMerchantNo());
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getPhoto(), JSONObject.toJSONString(param));
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getInteger("code") == 200) {
            bizMerchantInfoMapper.updateWhetherPhoto(bindPosDto.getMerchantNo());
            return AjaxResult.success("上传成功");
        } else {
            return AjaxResult.error("上传失败");
        }
    }

    @Override
    public AjaxResult wishCheckPartnerVideoUpload(BindPosDto bindPosDto) {
        JSONObject param = new JSONObject();
        param.put("video", bindPosDto.getVideo());
        param.put("merchantNo", bindPosDto.getMerchantNo());
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getVideo(), JSONObject.toJSONString(param));
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getInteger("code") == 200) {
            bizMerchantInfoMapper.updateWhethervideo(bindPosDto.getMerchantNo());
            System.out.println("上传签名视频成功");
            return AjaxResult.success("上传成功");
        } else {
            return AjaxResult.error("上传失败");
        }
    }

    @Override
    public List<PosOneMerchantInfo> getMyMerch(MerchantDTO merchantDTO) {
        merchantDTO.setQueryMonth(DateUtils.dateFormatStringToo(new Date()));
        if (merchantDTO.getPageNo() != null && merchantDTO.getPageSize() != null) {
            Integer pageNo = merchantDTO.getPageNo();
            Integer pageSize = merchantDTO.getPageSize();
            Integer start = (pageNo - 1) * pageSize;
            merchantDTO.setStart(start);
        }

        // POSP商户数量
        Long userId = merchantDTO.getUserId();
        BizMerchant bizMerchant = bizMerchantService.getMerchantByUserId(userId);
        // 查询商户数量  POSP
        merchantDTO.setMerchId(bizMerchant.getMerchId());
        String suffix = bizMerchantEntryMapper.selectSuffix(userId);
        String tableName ="";
        // 拼接机构表名称
        if(StringUtils.isNotBlank(suffix)){
            tableName="biz_transaction_amount_" + suffix;
        }else{
            tableName="biz_transaction_amount";
        }
        //直连的商户
        List<PosOneMerchantInfo> list = bizMerchantEntryMapper.getPosOneMerchantInfo(merchantDTO);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setQueryMonth(DateUtils.dateFormatStringToo(new Date()).substring(0, 7));
            list.get(i).setTableName(tableName);
            PosOneMerchantInfo pos = bizMerchantEntryMapper.getPosOneMerchantInfoAmount(list.get(i));
            list.get(i).setTransAmount(pos.getTransAmount());
            list.get(i).setType("1");  //直连
        }
        // 处理俩个商户表的分页数据问题
        List<PosOneMerchantInfo> listPosP = bizMerchantInfoMapper.getPospMerchantInfo(merchantDTO);
        for (int i = 0; i < listPosP.size(); i++) {
            listPosP.get(i).setQueryMonth(DateUtils.dateFormatStringToo(new Date()).substring(0, 7));
            listPosP.get(i).setTableName(tableName);
            PosOneMerchantInfo pos = bizMerchantEntryMapper.getPosOneMerchantInfoAmount(listPosP.get(i));
            listPosP.get(i).setTransAmount(pos.getTransAmount());
            listPosP.get(i).setType("2"); //posp
        }
        List<PosOneMerchantInfo> listAll = new ArrayList<>();
        listAll.addAll(list);
        listAll.addAll(listPosP);
        return listAll;
    }

    @Override
    public AjaxResult unbindMerchant(BindPosDto bindPosDto) {
        JSONObject param = new JSONObject();
        param.put("posCode", bindPosDto.getPosCode());
        param.put("merchantNo", bindPosDto.getMerchantNo());
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getUnbind(), JSONObject.toJSONString(param));
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");
        String msg = jsonObject.getString("msg");
        if (code == 200) {
            String status = "0";
         //   posMachineService.updateActivateStatus(bindPosDto.getPosCode(), status);
            //解绑
            relieve(bindPosDto.getPosCode());
            return AjaxResult.success(msg);
        } else {
            //查询是否有报件信息
            List<BizMerchantInfo> bizMerchantInfo = bizMerchantInfoMapper.getMerchantInfoRecord(bindPosDto.getPosCode());
            if(bizMerchantInfo.size()>0 && msg.contains("该机具没有绑定任何商户")){
                bizMerchantInfoMapper.updateSNByPosCode(bindPosDto.getPosCode());
                return AjaxResult.success("操作成功");
            }
            return AjaxResult.error(msg);
        }
    }

    @Override
    public int transferPos(BizMerchantInfo bizMerchantInfo) {
        int list = bizMerchantInfoMapper.transferPos1(bizMerchantInfo);
        int list2 = bizMerchantInfoMapper.transferPos2(bizMerchantInfo);
        return 0;
    }



    @Override
    public List<BizMerchantInfo>  getMerchantInfoRecord(String posCode) {
        return bizMerchantInfoMapper.getMerchantInfoRecord(posCode);
    }


    @Override
    public BizMerchantInfo getMerchantInfo(BizMerchantInfo bizMerchantInfo) {
        return bizMerchantInfoMapper.getMerchantInfo(bizMerchantInfo);
    }

    public final void relieve(String snCode) {
        String fictitiousSnCode = "";
        //获取merchId merchName
        BizMerchant bizMerchant = iBizMerchantService.selectBizMerchantBySN(snCode);
        //生成虚拟sn
        fictitiousSnCode = IdWorker.getIdStr();
        //把虚拟sn存入设备表
        posMachineService.insertPosMachine(fictitiousSnCode, bizMerchant.getMerchId());
        //获取该sn所有交易记录
        List<BizMerchTransactions> list = BizMerchTransactionsService.selectBizMerchTransactions(snCode);
        if (list.size() > 0) {
            //把所有交易记录存入到解绑交易记录表
            BizMerchTransactionsService.insertbizMerchTransactionsUnbund(list, bizMerchant.getMerchId(), bizMerchant.getMerchName());
            //交易记录sn换成虚拟sn
            BizMerchTransactionsService.updateBizMerchTransactionsBySN(snCode, fictitiousSnCode);
        }
        //获取激活信息  存解绑记录
        BizPosMachineStatusRecords bizPosMachineStatusRecords = machineStatusRecordsService.selectBizPosMachineStatusRecordsBysnCode(snCode);
        if(null!=bizPosMachineStatusRecords){
            machineStatusRecordsService.insertBizPosRecordsNew(bizPosMachineStatusRecords);
        }
        //删除激活表该sn数据
        machineStatusRecordsService.deleteBizPosRecordsNew(snCode);
        //删除报件 设备
        machineStatusRecordsService.deletebizentrySn(snCode);
        machineStatusRecordsMapper.updateBizmerchantInfoPosCode(snCode);
        //设备状态改为0
        iBizMerchantService.updataMerchantStatus(snCode);
        //运行函数
        iBizMerchantService.generateAllPosMerchantRelatedProcedure();
    }

    private String agentid(){
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        String suffix=bizMerchantInfoMapper.getSuffix(sysUserman.getUserId());
        return bizMerchantInfoMapper.getAgentId(suffix);
    }

//    public static void main(String[] args) {
//        System.out.println(IdWorker.getIdStr());
//    }

    @Override
    public String getAgentRate(String posCode) {
        return bizMerchantInfoMapper.getAgentRate(posCode);
    }

    @Override
    public String getDeptIdByPosCode(String posCode) {
        return bizMerchantInfoMapper.getDeptIdByPosCode(posCode);
    }

    @Override
    public String getMerchantInfoStatus(String posCode) {
        return bizMerchantInfoMapper.getMerchantInfoStatus(posCode);
    }

    @Override
    public AjaxResult plUpdateFee(){
        List<BizMerchantInfo> infos = bizMerchantInfoMapper.getPlUpdateFeeList();
        for(BizMerchantInfo info : infos){
            info.setFeeId(100653);
            info.setImg(null);
            updateMerchantFee(info);
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult updateInfoFeePlusTenThousandsOne() {
        List<BizMerchantInfo> infos = bizMerchantInfoMapper.getForFee();
        for(BizMerchantInfo info : infos){
            int feeId = info.getFeeId();
//            System.out.println(info.getMerchantCode()+"原费率"+feeId);
//            if(info.getFeeId() == 10053){
//                feeId = 10054;
//            }else if (info.getFeeId() == 10054){
//                feeId = 10055;
//            }else if (info.getFeeId() == 10055){
                feeId = 10057;
//            }else if (info.getFeeId() == 10057){
//                feeId = 10058;
//            }else if (info.getFeeId() == 10058){
//                feeId = 10059;
//            }else if (info.getFeeId() == 10059){
//                feeId = 10060;
//            }else if (info.getFeeId() == 10060){
//                feeId = 10061;
//            }
            System.out.println(info.getMerchantCode()+"新费率"+feeId);
            updateFee(info.getMerchantCode(),feeId);
        }
        return AjaxResult.success();
    }

    public void updateFee(String merchantCode ,int feeId){
        JSONObject feeParam = new JSONObject();
        feeParam.put("merchantCode",merchantCode);
        feeParam.put("feeId",feeId);
        System.out.println("请求参数--》》》》" + JSONObject.toJSONString(feeParam));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getUpdateFee(), JSONObject.toJSONString(feeParam));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if ("200".equals(code)) {
            bizMerchantInfoMapper.updateMerchantFee(merchantCode,feeId);
            System.out.println(merchantCode+"调整费率成功"+feeId);
        }else{
            bizMerchantInfoMapper.updateFailFee(merchantCode);
            System.out.println(merchantCode+"调整费率失败");
        }
    }

    @Override
    public AjaxResult updateMerchantFee(BizMerchantInfo bizMerchantInfo) {
        if(null == bizMerchantInfo.getFeeId()){
            return  AjaxResult.error("请选择费率");
        }
        // 查询设备是哪个渠道
        BizMerchantInfo merchantInfo = bizMerchantInfoService.getMerchantInfo(bizMerchantInfo);
        BizPosMachine bizPosMachine = bizPosMachineMapper.selectPosMachineBySn(merchantInfo.getPosCode());
        if ("17".equals(bizPosMachine.getChannel())){
            JSONObject param = new JSONObject();
            param.put("merchNo",bizMerchantInfo.getMerchantCode());
            param.put("deviceSn",merchantInfo.getPosCode());
            param.put("feeId",bizMerchantInfo.getFeeId());
            // 传一个 机构id
            SysUser sysUser = sysUserMapper.selectUserByMerchId(bizPosMachine.getMerchId());
            // 查询出哪个机构的
            param.put("agentId",sysUser.getJlAgent());
            return posTransactionNoticeService.jlUpdateFee(param);
        }
        JSONObject feeParam = new JSONObject();
        feeParam.put("merchantCode",bizMerchantInfo.getMerchantCode());
        feeParam.put("feeId",bizMerchantInfo.getFeeId());
        String img=bizMerchantInfo.getImg();
        if(null!=img)
            feeParam.put("qbFaceRecognition", img.substring(img.indexOf(",")+1)); //  图片bas64
        System.out.println("请求参数--》》》》" + JSONObject.toJSONString(feeParam));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getUpdateFee(), JSONObject.toJSONString(feeParam));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if ("200".equals(code)) {
            bizMerchantInfoMapper.updateMerchantFee(bizMerchantInfo.getMerchantCode(),bizMerchantInfo.getFeeId());
//            System.out.println("商户号"+bizMerchantInfo.getMerchantCode());
//            bizMerchantInfoMapper.insertTestForRule(bizMerchantInfo.getMerchantCode());

            return  AjaxResult.success("费率修改成功");
        }else{

            return AjaxResult.error("费率修改失败");
        }
    }

    @Override
    public JSONObject updateSettleAccount(BizMerchantInfo merchantInfo) {
        JSONObject legalPerson = new JSONObject();
        //修改
        if ("".equals(merchantInfo.getMerchantCode()) && merchantInfo.getMerchantCode() == null) {
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "商户编号不能为空");
            return erro;
        }
        BizMerchantInfo bizMerchantInfo = bizMerchantInfoService.getMerchantInfo(merchantInfo);
        if(!"3".equals(bizMerchantInfo.getAuditStatus()) &&
                !"1".equals(bizMerchantInfo.getSettleAccountStatus())
                && !"3".equals(bizMerchantInfo.getSettleAccountStatus())){
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "修改结算卡中,请勿再次修改");
            return erro;
        }
//        bizMerchantInfo.setFeeId(merchantInfo.getFeeId());  //  费率id
        bizMerchantInfo.setBankCardPic(merchantInfo.getBankCardPic()); // 银行卡照片
        bizMerchantInfo.setBankCardAccount(merchantInfo.getBankCardAccount()); //银行卡号
        bizMerchantInfo.setBankCardHolder(merchantInfo.getBankCardHolder()); // 开户名
        bizMerchantInfo.setBankCardPhone(merchantInfo.getBankCardPhone()); // 预留手机好
        bizMerchantInfo.setUnionpayCode(merchantInfo.getUnionpayCode());//联行卡号
//        bizMerchantInfo.setProvinceNo(merchantInfo.getProvinceNo()); // 开户省
//        bizMerchantInfo.setCityNo(merchantInfo.getCityNo()); // 开户市
//        bizMerchantInfo.setAreaNo(merchantInfo.getAreaNo()); // 开户区
        bizMerchantInfo.setBankCode(merchantInfo.getBankCode()); // 银行编码
        bizMerchantInfo.setBankSite(merchantInfo.getBankSite()); // 网点
        legalPerson.put("merchantCode", bizMerchantInfo.getMerchantCode());
        legalPerson.put("certificateEndDate", bizMerchantInfo.getCertificateEndDate()); //  证件有效期截止日期（例：1949-10-01）;
        legalPerson.put("certificateNo", bizMerchantInfo.getCertificateNo());   //  法人证件号码
        legalPerson.put("certificateStartDate", bizMerchantInfo.getCertificateStartDate()); //  证件有效期开始日期（例：1949-10-01）
        legalPerson.put("certificatesBackPic", bizMerchantInfo.getCertificatesBackPic()); //  证件国徽面
        legalPerson.put("certificatesFrontPic", bizMerchantInfo.getCertificatesFrontPic()); //  证件人脸面
        legalPerson.put("idcardHandPic", bizMerchantInfo.getIdcardHandPic()); //  手持身份证照片（与法人人脸识别留存照片两者必须有一个不为空）; 例如:picture2/手持身份证照片.jpg
        legalPerson.put("legalPersonName", bizMerchantInfo.getLegalPersonName()); //  法人姓名
        legalPerson.put("address", bizMerchantInfo.getAddress()); //  详细地址
        //通用一个人
        legalPerson.put("applicant", bizMerchantInfo.getLegalPersonName()); //  联系人（固定为法人名称
        legalPerson.put("areaNo", bizMerchantInfo.getAreaNo()); //  区县代码
        legalPerson.put("cityNo", bizMerchantInfo.getCityNo()); //   城市编号
        legalPerson.put("clientServicePhoneNo", bizMerchantInfo.getClientServicePhoneNo()); //   客服电话
        legalPerson.put("contactPhoneNo", bizMerchantInfo.getContactPhoneNo()); //  联系电话
        legalPerson.put("merchantName", bizMerchantInfo.getLegalPersonName()); //  商户名称（固定格式：前缀”商户_“+法人名称）
        legalPerson.put("merchantShortHand", bizMerchantInfo.getMerchantShortHand()); //  商户简写
        legalPerson.put("provinceNo", bizMerchantInfo.getProvinceNo()); //  省份代码（调用修改时不需要传入该字段）
        JSONObject settleAccountInfo = new JSONObject();
        legalPerson.put("bankCardAccount", bizMerchantInfo.getBankCardAccount()); //  银行账号
        legalPerson.put("bankCardHolder", bizMerchantInfo.getBankCardHolder()); //   开户名
        legalPerson.put("bankCardPhone", bizMerchantInfo.getBankCardPhone()); //  银行卡预留手机号
        legalPerson.put("bankCardPic", bizMerchantInfo.getBankCardPic()); //  银行卡照片
        legalPerson.put("bankCity", bizMerchantInfo.getBankCity()); //  开户银行城市
        legalPerson.put("bankCode", bizMerchantInfo.getBankCode()); //  银行编码
        legalPerson.put("bankProvince", bizMerchantInfo.getBankProvince()); //  开户银行省份
        legalPerson.put("bankSite", bizMerchantInfo.getBankSite()); //  开户行网点
        legalPerson.put("unionpayCode", bizMerchantInfo.getUnionpayCode()); //  开户支行联行号
        legalPerson.put("phone", bizMerchantInfo.getPhone()); //  注册手机
        String userName = IdWorker.getIdStr();
        legalPerson.put("userName", userName); //  用户名（1、唯一；每次请求都要换一个新的，因为涉及到其他部门接口，不是一个事务内2、用uuid即可）（调用修改时不需要传入该字段）
        legalPerson.put("activeAddress", bizMerchantInfo.getActiveAddress()); //  商户活体检测地址
        legalPerson.put("activeLatitude", bizMerchantInfo.getActiveLatitude()); //  	商户活体检测地址纬度
        legalPerson.put("activeLongitude", bizMerchantInfo.getActiveLongitude()); //  	商户活体检测地址经度
        legalPerson.put("registerAddress", bizMerchantInfo.getRegisterAddress()); //  商户注册地址
        legalPerson.put("registerLatitude", bizMerchantInfo.getRegisterLatitude()); //  商户注册地址纬度
        legalPerson.put("registerLongitude", bizMerchantInfo.getRegisterLongitude()); //  商户注册地址经度
        legalPerson.put("agentid", this.agentid());
        String img=merchantInfo.getImg();
        if(null!=img)
            legalPerson.put("qbFaceRecognition", img.substring(img.indexOf(",")+1)); //  图片bas64
//        legalPerson.put("feeId", bizMerchantInfo.getFeeId());
        legalPerson.put("posCode", bizMerchantInfo.getPosCode());
        //把结算卡状态修改为  进行中
        bizMerchantInfoMapper.updateSettleAccountStatus(bizMerchantInfo.getMerchantCode());
        legalPerson.put("bankCardBackPic",bizMerchantInfo.getBankCardBackPic());
        System.out.println("请求参数--》》》》" + JSONObject.toJSONString(legalPerson));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getUpdateSettleAccount(), JSONObject.toJSONString(legalPerson));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if (code.equals("200")) {  //成功
            JSONObject data = jsonObject.getJSONObject("data");
            BizMerchantInfo bizMerchantInfo1 = new BizMerchantInfo();
            bizMerchantInfo1.setMerchantCode(bizMerchantInfo.getMerchantCode());
            bizMerchantInfo1.setMerchantDesc(data.getString("merchantDesc"));
            if("1".equals(data.getString("auditStatus"))){
                //审核失败 , 更新审核提示
                bizMerchantInfo1.setSettleAccountStatus("1");
                bizMerchantInfoMapper.updateSettleAccountStatusByMerchantCode(bizMerchantInfo1);
            }else if("2".equals(data.getString("auditStatus"))){
                // 人工审核 更新审核提示
                bizMerchantInfo1.setSettleAccountStatus("2");
                bizMerchantInfoMapper.updateSettleAccountStatusByMerchantCode(bizMerchantInfo1);
            }else if("3".equals(data.getString("auditStatus"))){
                //审核成功 更新审核提示
                String desc = data.getString("desc");
                bizMerchantInfo.setMerchantDesc(desc);
                bizMerchantInfo.setUpdateTime(new Date());
                bizMerchantInfo.setUpdateResult(data.getString("updateResult"));
                bizMerchantInfo.setSettleAccountStatus("3");
                //更新自己的库
                bizMerchantInfoService.updateMerchantsInfoByMerchantCode(bizMerchantInfo);
            }
            return jsonObject;
        } else {
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "操作失败:"+jsonObject.getString("msg"));
            return erro;
        }
    }


    @Override
    @Transactional
    public int updateSettleAccountStatusByMerchantCode(BizMerchantInfo bizMerchantInfo) {
        //推送消息
        BizMerchantInfo merchantInfo = bizMerchantInfoMapper.getMerchantInfo(bizMerchantInfo);
        BizMerchant merchantByMerchId = bizMerchantService.getMerchantByMerchId(merchantInfo.getMerchId());
        //推送审核消息
        String fanXianMess = bizMerchantInfo.getMerchantDesc();  // 详细信息
        BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
        fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
        fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
        fanXianMessageRecords.setReadStatus(0); // 消息未读
        fanXianMessageRecords.setAdviceType(1); // 业务消息
        webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
        if ("1".equals(bizMerchantInfo.getSettleAccountStatus())){ // 失败
            bizMerchantInfo.setSettleAccountStatus("1");
        }else if ("2".equals(bizMerchantInfo.getSettleAccountStatus())){  // 进行中
            bizMerchantInfo.setSettleAccountStatus("2");
        }else if ("3".equals(bizMerchantInfo.getSettleAccountStatus())){  // 成功
            bizMerchantInfo.setSettleAccountStatus("3");
        }
        return bizMerchantInfoMapper.updateSettleAccountByMerchantCode(bizMerchantInfo);
    }

    @Override
    public BizMerchantInfo getMerchantInfoBySn(String snCode) {
        return bizMerchantInfoMapper.getMerchantInfoBySn(snCode);
    }

    @Override
    public BizMerchantInfo getMerchantInfoByMerchantId(String merchantId) {
        return bizMerchantInfoMapper.getMerchantInfoByMerchantId(merchantId);
    }

    @Override
    public List<BizTransactionCountDTO> selectBizMerchantInfoByMerchantNo(BizMerchantEntry bizMerchantEntry) {
        return bizMerchantInfoMapper.selectBizMerchantInfoByMerchantNo(bizMerchantEntry);
    }

    @Override
    public BizTransactionCountDTO selectBizMerchantEntryMerchNameAndTime(String merchantNo) {
        return bizMerchantInfoMapper.selectBizMerchantEntryMerchNameAndTime(merchantNo);
    }


    @Override
    public AjaxResult addMerchantsInfoForGDB(BizMerchantEpspBinding bizMerchantEpspBinding) throws Exception {
        BizMerchantEpspBinding old = bizMerchantInfoMapper.checkIsExists(bizMerchantEpspBinding.getBankCardNo());
        if(old != null){
            return AjaxResult.error("此卡已绑定");
        }
        BizMerchantInfo info = bizMerchantInfoMapper.getInfoByMerchantCode(bizMerchantEpspBinding.getMerchantCode());
        String userNameParam = bizMerchantEpspBinding.getUserName();
        String certificatesNoParam = bizMerchantEpspBinding.getCertificatesNo();
        String bankCardNoParam = bizMerchantEpspBinding.getBankCardNo();
        String phoneNumParam = bizMerchantEpspBinding.getPhoneNum();
        String cvnParam = bizMerchantEpspBinding.getCvn();
        String expiredParam = bizMerchantEpspBinding.getExpired();
        String province = bizMerchantEpspBinding.getProvince();
        String city = bizMerchantEpspBinding.getCity();
        String area = bizMerchantEpspBinding.getArea();
        String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
        String mchtOrderNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); // 交易编号,商户侧唯一
        JSONObject params = new JSONObject();
        params.put("userName",userNameParam);
        params.put("certificatesNo",certificatesNoParam);
        params.put("bankCardNo",bankCardNoParam);
        params.put("phoneNum",phoneNumParam);
        params.put("cvn",cvnParam);
        params.put("expired",expiredParam);
        params.put("mchtOrderNo",mchtOrderNo);
        params.put("nonceStr",nonceStr);
        params.put("province",province);
        params.put("city",city);
        params.put("area",area);
        params.put("merchantCode",bizMerchantEpspBinding.getMerchantCode());
        System.out.println(bizMerchantEpspBinding.getMerchantCode()+"EPSP绑定请求参数---->"+params);
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getAddMerchantsInfoForGDB(), JSONObject.toJSONString(params));
        JSONObject jsonObject = JSONObject.parseObject(result);
//        String code = jsonObject.getString("code");
//        String msg = jsonObject.getString("msg");
        JSONObject json = jsonObject.getJSONObject("data");
        System.out.println(json);
        ProtocolPayBindCardResponse response = JSONObject.parseObject(String.valueOf(json), ProtocolPayBindCardResponse.class);
        bizMerchantEpspBinding.setCustomerCode(response.getCustomerCode());
        bizMerchantEpspBinding.setMemberId(response.getMemberId());
        bizMerchantEpspBinding.setMchtOrderNo(response.getMchtOrderNo());
        bizMerchantEpspBinding.setUserName(userNameParam);
        bizMerchantEpspBinding.setCertificatesNo(certificatesNoParam);
        bizMerchantEpspBinding.setBindingTime(new Date());
        bizMerchantEpspBinding.setNonceStr(nonceStr);
        bizMerchantEpspBinding.setProvince(province);
        bizMerchantEpspBinding.setCity(city);
        bizMerchantEpspBinding.setArea(area);
        bizMerchantEpspBinding.setBankCardType("credit");
        if("0000".equals(response.getReturnCode())){
            bizMerchantEpspBinding.setSmsno(response.getSmsNo());
            bizMerchantEpspBinding.setReturnCode("0000");
            bizMerchantEpspBinding.setIsOpen(response.getIsOpen());
            iBizMerchantEpspBindingService.save(bizMerchantEpspBinding);
            System.out.println(bizMerchantEpspBinding.getMerchantCode()+"绑定成功,数据保存成功");
            return AjaxResult.success("提交成功待确认",response);
        }else{
            bizMerchantEpspBinding.setReturnCode(response.getReturnCode());
            bizMerchantEpspBinding.setReturnMsg(response.getReturnMsg());
            bizMerchantEpspBinding.setSmsno(response.getSmsNo());
            bizMerchantEpspBinding.setIsOpen("false");
            iBizMerchantEpspBindingService.save(bizMerchantEpspBinding);
            System.out.println(bizMerchantEpspBinding.getMerchantCode()+"绑定失败,数据保存成功"+response.getReturnMsg());
            return AjaxResult.error("绑定失败"+response.getReturnMsg());
        }

    }

    @Override
    public AjaxResult smsCodeConfirm(BizMerchantEpspBinding bizMerchantEpspBinding) throws Exception {
        LambdaQueryWrapper<BizMerchantEpspBinding> lqw = Wrappers.lambdaQuery();
        lqw.eq(BizMerchantEpspBinding::getMchtOrderNo,bizMerchantEpspBinding.getMchtOrderNo());
        BizMerchantEpspBinding bizMerchantEpspBindingData = iBizMerchantEpspBindingService.getOne(lqw);
        if(bizMerchantEpspBindingData == null){
            return AjaxResult.error("数据异常,请联系服务商");
        }
        if("".equals(bizMerchantEpspBinding.getSmsCode()) || bizMerchantEpspBinding.getSmsCode() == null){
            return AjaxResult.error("请填写验证码");
        }
        JSONObject params = new JSONObject();
        params.put("smsno",bizMerchantEpspBindingData.getSmsno());
        params.put("smsCode",bizMerchantEpspBinding.getSmsCode());
        params.put("memberId",bizMerchantEpspBindingData.getMemberId());
        params.put("customerCode",bizMerchantEpspBindingData.getCustomerCode());
        params.put("mchtOrderNo",bizMerchantEpspBinding.getMchtOrderNo());
        params.put("nonceStr",UUID.randomUUID().toString().replaceAll("-", ""));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getSmsCodeConfirm(), JSONObject.toJSONString(params));

        JSONObject jsonObject = JSONObject.parseObject(result);
//        String code = jsonObject.getString("code");
//        String msg = jsonObject.getString("msg");
        JSONObject json = jsonObject.getJSONObject("data");
        System.out.println(json);
        ProtocolPayBindCardConfirmResponse response = JSONObject.parseObject(String.valueOf(json), ProtocolPayBindCardConfirmResponse.class);
        if("0000".equals(response.getReturnCode())){
            bizMerchantEpspBindingData.setReturnCode(response.getReturnCode());
            bizMerchantEpspBindingData.setProtocol(response.getProtocol());
            bizMerchantEpspBindingData.setReturnMsg(response.getReturnMsg());
            bizMerchantEpspBindingData.setSmsno(response.getSmsNo());
            bizMerchantEpspBindingData.setBindingTime(new Date());
            iBizMerchantEpspBindingService.saveOrUpdate(bizMerchantEpspBindingData);
            System.out.println(bizMerchantEpspBindingData+"绑卡成功");
            return AjaxResult.success("绑卡成功");
        }else{
            bizMerchantEpspBindingData.setReturnCode(response.getReturnCode());
            bizMerchantEpspBindingData.setReturnMsg(response.getReturnMsg());
            iBizMerchantEpspBindingService.saveOrUpdate(bizMerchantEpspBindingData);
            System.out.println(bizMerchantEpspBindingData+"绑卡失败"+response.getReturnMsg());
            return AjaxResult.error("绑卡失败"+response.getReturnMsg());
        }
    }

    @Override
    public AjaxResult GDBProvince() {
        List<BizGdbArea> bizGdbArea = bizMerchantInfoMapper.GDBProvince();
        return AjaxResult.success("省份",bizGdbArea);
    }



    @Override
    public AjaxResult GDBCity(BizGdbArea bizGdbArea) {
        List<BizGdbArea> bizGdbArea1 = bizMerchantInfoMapper.GDBCity(bizGdbArea);
        return AjaxResult.success("市",bizGdbArea1);
    }

    @Override
    public AjaxResult GDBArea(BizGdbArea bizGdbArea) {
        List<BizGdbArea> bizGdbArea1 = bizMerchantInfoMapper.GDBCity(bizGdbArea);
        return AjaxResult.success("区",bizGdbArea1);
    }

    @Override
    public List<BizMerchantEpspBinding> backAccountList(BizMerchantEpspBinding bizMerchantEpspBinding) {
        return iBizMerchantEpspBindingService.backAccountList(bizMerchantEpspBinding);
    }
    @Override
    @Transactional
    public JSONObject addMerchantsKDBInfo(BizMerchantInfo bizMerchantInfo) {
        JSONObject legalPerson = new JSONObject();
        String posCode = bizMerchantInfoMapper.selectMerchantInfoSn(bizMerchantInfo.getPosCode());
        if (StringUtils.isNotBlank(posCode)) {
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "已存在商户");
            return  erro;
        }
        BizPosMachine posMachineBySnCode = posMachineService.getPosMachineBySnCode(bizMerchantInfo.getPosCode());
        if(posMachineBySnCode == null){
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "设备不存在");
            return  erro;
        }
        // 代理
        BizMerchant merchantByMerchId = bizMerchantService.getMerchantByMerchId(posMachineBySnCode.getMerchId());

        legalPerson.put("certificateEndDate", bizMerchantInfo.getCertificateEndDate()); //  证件有效期截止日期（例：1949-10-01）;
        legalPerson.put("certificateNo", bizMerchantInfo.getCertificateNo());   //  法人证件号码
        legalPerson.put("certificateStartDate", bizMerchantInfo.getCertificateStartDate()); //  证件有效期开始日期（例：1949-10-01）
        legalPerson.put("certificatesBackPic", bizMerchantInfo.getCertificatesBackPic()); //  证件国徽面
        legalPerson.put("certificatesFrontPic", bizMerchantInfo.getCertificatesFrontPic()); //  证件人脸面
        legalPerson.put("idcardHandPic", bizMerchantInfo.getIdcardHandPic()); //  手持身份证照片（与法人人脸识别留存照片两者必须有一个不为空）; 例如:picture2/手持身份证照片.jpg
        legalPerson.put("legalPersonName", bizMerchantInfo.getLegalPersonName()); //  法人姓名
        legalPerson.put("address", bizMerchantInfo.getAddress()); //  详细地址
        //通用一个人
        legalPerson.put("applicant", bizMerchantInfo.getLegalPersonName()); //  联系人（固定为法人名称
        legalPerson.put("areaNo", bizMerchantInfo.getAreaNo()); //  区县代码
        legalPerson.put("cityNo", bizMerchantInfo.getCityNo()); //   城市编号
        legalPerson.put("provinceName", bizMerchantInfo.getProvinceName()); //   城市编号
        legalPerson.put("cityName", bizMerchantInfo.getCityName()); //   城市编号
        legalPerson.put("areaName", bizMerchantInfo.getAreaName()); //   城市编号
        legalPerson.put("clientServicePhoneNo", bizMerchantInfo.getClientServicePhoneNo()); //   客服电话
        legalPerson.put("contactPhoneNo", bizMerchantInfo.getContactPhoneNo()); //  联系电话

        legalPerson.put("merchantName", bizMerchantInfo.getLegalPersonName()); //  商户名称（固定格式：前缀”商户_“+法人名称）
        legalPerson.put("merchantShortHand", bizMerchantInfo.getMerchantShortHand()); //  商户简写
        legalPerson.put("provinceNo", bizMerchantInfo.getProvinceNo()); //  省份代码（调用修改时不需要传入该字段）
        legalPerson.put("bankCardAccount", bizMerchantInfo.getBankCardAccount()); //  银行账号
        legalPerson.put("bankCardHolder", bizMerchantInfo.getBankCardHolder()); //   开户名
        legalPerson.put("bankCardPhone", bizMerchantInfo.getBankCardPhone()); //  银行卡预留手机号
        legalPerson.put("bankCardPic", bizMerchantInfo.getBankCardPic()); //  银行卡照片
        legalPerson.put("bankCity", bizMerchantInfo.getBankCity()); //  开户银行城市
        legalPerson.put("bankCode", bizMerchantInfo.getBankCode()); //  银行编码
        legalPerson.put("bankProvince", bizMerchantInfo.getBankProvince()); //  开户银行省份
        legalPerson.put("bankSite", bizMerchantInfo.getBankSite()); //  开户行网点
        legalPerson.put("unionpayCode", bizMerchantInfo.getUnionpayCode()); //  开户支行联行号
        legalPerson.put("phone", bizMerchantInfo.getPhone()); //  注册手机
        String userName = IdWorker.getIdStr();
        legalPerson.put("userName", userName); //  用户名（1、唯一；每次请求都要换一个新的，因为涉及到其他部门接口，不是一个事务内2、用uuid即可）（调用修改时不需要传入该字段）
        legalPerson.put("activeAddress", bizMerchantInfo.getActiveAddress()); //  商户活体检测地址
        legalPerson.put("activeLatitude", bizMerchantInfo.getActiveLatitude()); //  	商户活体检测地址纬度
        legalPerson.put("activeLongitude", bizMerchantInfo.getActiveLongitude()); //  	商户活体检测地址经度
        legalPerson.put("registerAddress", bizMerchantInfo.getRegisterAddress()); //  商户注册地址
        legalPerson.put("registerLatitude", bizMerchantInfo.getRegisterLatitude()); //  商户注册地址纬度
        legalPerson.put("registerLongitude", bizMerchantInfo.getRegisterLongitude()); //  商户注册地址经度
        legalPerson.put("agentid", this.agentid());
        legalPerson.put("posCode", bizMerchantInfo.getPosCode());
        legalPerson.put("feeId", bizMerchantInfo.getFeeId());
        legalPerson.put("faceAuthFlag", bizMerchantInfo.getFaceAuthFlag());
        legalPerson.put("faceAuthOrderNo", bizMerchantInfo.getFaceAuthOrderNo());
        //企业进件20240116新增
        legalPerson.put("settAccMark", bizMerchantInfo.getSettAccMark());
        legalPerson.put("busNature", bizMerchantInfo.getBusNature());
        legalPerson.put("busRegNo", bizMerchantInfo.getBusRegNo());
        legalPerson.put("busRegType", bizMerchantInfo.getBusRegType());
        legalPerson.put("receiptProImg", bizMerchantInfo.getReceiptProImg());
        legalPerson.put("busiLicenseImg", bizMerchantInfo.getBusiLicenseImg());
        legalPerson.put("cashDeskImg", bizMerchantInfo.getCashDeskImg());
        legalPerson.put("busiPlaceImg", bizMerchantInfo.getBusiPlaceImg());
        legalPerson.put("busiDoorImg", bizMerchantInfo.getBusiDoorImg());
        legalPerson.put("bankAboveImg", bizMerchantInfo.getBankAboveImg());
        legalPerson.put("settleProImg", bizMerchantInfo.getSettleProImg());
        legalPerson.put("otherImg1", bizMerchantInfo.getOtherImg1());
        legalPerson.put("busRegStartDt", bizMerchantInfo.getBusRegStartDt());
        legalPerson.put("busRegEndDt", bizMerchantInfo.getBusRegEndDt());
        legalPerson.put("legalpersonIsSett", bizMerchantInfo.getLegalpersonIsSett());
        legalPerson.put("settCrpNo", bizMerchantInfo.getSettCrpNo());
        legalPerson.put("settCrpAboveImg", bizMerchantInfo.getSettCrpAboveImg());
        legalPerson.put("settCrpBelovImg", bizMerchantInfo.getSettCrpBelovImg());
        legalPerson.put("nonCrpNmSettleProImg", bizMerchantInfo.getNonCrpNmSettleProImg());
        legalPerson.put("mercTypeMCC", bizMerchantInfo.getMccCd());
        legalPerson.put("bankName", bizMerchantInfo.getBankName());
        legalPerson.put("reqNo", bizMerchantInfo.getReqNo());
        System.out.println("请求参数--》》》》" + JSONObject.toJSONString(legalPerson));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getMerchantsKDBInfo(), JSONObject.toJSONString(legalPerson));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        JSONObject data = jsonObject.getJSONObject("data");
        String desc="";
        if(data!=null){
            desc = data.getString("desc");
        }else{
            desc=msg;
        }
        jsonObject.put("uuid",userName);
        if (code.equals("200")) {  //成功
            String merchantId = data.getString("merchantId");
            String merchantNo = data.getString("merchantNo");
            System.out.println("POSP商户审核成功"+bizMerchantInfo.getLegalPersonName());
            System.out.println("POSP商户标号"+merchantNo);
            String sn = data.getString("sn");
            bizMerchantInfo.setMerchantId(merchantId);
            bizMerchantInfo.setMerchantKey(data.getString("merchantKey"));
            bizMerchantInfo.setMasterKeys(data.getString("masterkeys"));
            bizMerchantInfo.setValidationValue(data.getString("validationValue"));
            bizMerchantInfo.setAuditStatus("2");
            bizMerchantInfo.setSn(sn);
            bizMerchantInfo.setMerchId(posMachineBySnCode.getMerchId());
            bizMerchantInfo.setMerchantDesc(desc);
            bizMerchantInfo.setMerchantCode(merchantNo);
            bizMerchantInfo.setCertificateType("1");
            bizMerchantInfo.setProductType("POS");
            bizMerchantInfo.setMccCode("4812");
            bizMerchantInfo.setMerchantSubType("4");
            bizMerchantInfo.setMerchantType("1");
            bizMerchantInfo.setBankCardAccountType("1");
            bizMerchantInfo.setUserName(userName);
            bizMerchantInfo.setMerchantLevel(data.getString("merchantLevel"));
            bizMerchantInfo.setRegisterTime(DateUtils.dateFormatString(new Date()));
            bizMerchantInfo.setClientServicePhoneNo(bizMerchantInfo.getBankCardPhone());
            bizMerchantInfo.setMerchantName(bizMerchantInfo.getLegalPersonName());
            if(StringUtils.isBlank(bizMerchantInfo.getApplicant())){
                bizMerchantInfo.setApplicant(bizMerchantInfo.getLegalPersonName());
            }
            bizMerchantInfo.setRegisterAddress(bizMerchantInfo.getActiveAddress());
            bizMerchantInfo.setRegisterLatitude(bizMerchantInfo.getActiveLatitude());
            bizMerchantInfo.setRegisterLongitude(bizMerchantInfo.getActiveLongitude());
            if(bizMerchantInfo.getBusNature() == null ){// 3 是小微
                bizMerchantInfo.setXwSigning("1");// 秒付通家原来小程序他们继续用, 但是没这个参数
                bizMerchantInfo.setBusNature("3");
            }else{
               if("3".equals(bizMerchantInfo.getBusNature())){
                   bizMerchantInfo.setXwSigning("1");
               }else{
                   bizMerchantInfo.setQySigning("1");
               }
            }
            //存到自己的库里
            boolean save = bizMerchantInfoService.save(bizMerchantInfo);
            //推送审核成功消息
            String fanXianMess = "SN：" + bizMerchantInfo.getPosCode() + "审核成功";
            BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
            fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
            fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
            fanXianMessageRecords.setReadStatus(0); // 消息未读
            fanXianMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
            return jsonObject;
        } else {
            //推送审核成功消息
            String fanXianMess = "SN：" + bizMerchantInfo.getPosCode() + "审核失败"+desc;
            BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
            fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
            fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
            fanXianMessageRecords.setReadStatus(0); // 消息未读
            fanXianMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            if(null!=data){
                JSONObject mate = data.getJSONObject("mate");
                if(null!=mate){
                    erro.put("msg", msg+":"+mate.getString("msg"));
                }else{
                    erro.put("msg", msg);
                }
            }else{
                erro.put("msg", msg);
            }
            return erro;
        }

    }
    public JSONObject kdbCallback(BizMerchantInfo bizMerchantInfo) {
        JSONObject erro = new JSONObject();
        if(null!=bizMerchantInfo){
            bizMerchantInfoMapper.updateKDBInfo(bizMerchantInfo);
            erro.put("code", 200);
            erro.put("msg", "接收成功");
            return erro;
        }
        erro.put("code", 500);
        erro.put("msg", "接收失败");
        return erro;
    }
    public JSONObject kdbBindCallback(BizMerchantInfo bizMerchantInfo) {
        JSONObject erro = new JSONObject();
        if(null!=bizMerchantInfo){
            System.out.println("开店宝绑定接口");
            if("1".equals(bizMerchantInfo.getBindStatus())){
                System.out.println("绑定成功");
                bizMerchantInfoMapper.kdbBindCallback(bizMerchantInfo);
                BizMerchantInfo info=bizMerchantInfoMapper.getInfoByMerchantCode(bizMerchantInfo.getMerchantCode());
                BizPosMachine bizPosMachine = posMachineService.selectPosBySnCode(info.getPosCode());
                BizMerchantEntry bizMerchantEntry = new BizMerchantEntry();
                bizMerchantEntry.setSn(info.getPosCode()); //sn
                bizMerchantEntry.setCertificateno(info.getCertificateNo()); //身份证号
                bizMerchantEntry.setPhone(info.getBankCardPhone());  // 预留手机号
                bizMerchantEntry.setApplicant(info.getLegalPersonName()); // 姓名
                bizMerchantEntry.setMerchantNo(info.getMerchantCode()); // 姓名
                bizMerchantEntry.setTerminalCode(bizPosMachine.getPosType()); // 姓名
                //激活表插入数据
                int ok = recordsService.snRecordsOneVersion(bizMerchantEntry);
                bizPosMachineMapper.generateAllPosMerchantRelatedProcedure();// 运行函数
                //更新设备表绑定状态
                System.out.println("绑定成功" + info.getPosCode() + DateUtils.dateFormatString(new Date()));
            }else{
                System.out.println("绑定失败");
            }
            erro.put("code", 200);
            erro.put("msg", "接收成功");
            return erro;
        }
        erro.put("code", 500);
        erro.put("msg", "接收失败");
        return erro;
    }
    /**
     * 线上pos报件
     * @param bizMerchantInfo
     * @return
     */
    @Override
    @Transactional
    public AjaxResult addMerchantsOnline(BizMerchantInfo bizMerchantInfo) {
        JSONObject legalPerson = new JSONObject();
        //设置默认费率为0.6
        if(null==bizMerchantInfo.getFeeId()||"".equals(bizMerchantInfo.getFeeId())){
            bizMerchantInfo.setFeeId(DEFAULT_FEE_ID);
        }
        Long userId = LoginUserUtils.getLoginUserId();
        // 代理
        BizMerchant merchantByMerchId = bizMerchantService.getMerchantByUserId(userId);
        legalPerson.put("certificateEndDate", bizMerchantInfo.getCertificateEndDate()); //  证件有效期截止日期（例：1949-10-01）;
        legalPerson.put("certificateNo", bizMerchantInfo.getCertificateNo());   //  法人证件号码
        legalPerson.put("certificateStartDate", bizMerchantInfo.getCertificateStartDate()); //  证件有效期开始日期（例：1949-10-01）
        legalPerson.put("certificatesBackPic", bizMerchantInfo.getCertificatesBackPic()); //  证件国徽面
        legalPerson.put("certificatesFrontPic", bizMerchantInfo.getCertificatesFrontPic()); //  证件人脸面
        legalPerson.put("idcardHandPic", bizMerchantInfo.getIdcardHandPic()); //  手持身份证照片（与法人人脸识别留存照片两者必须有一个不为空）; 例如:picture2/手持身份证照片.jpg
        legalPerson.put("legalPersonName", bizMerchantInfo.getLegalPersonName()); //  法人姓名
        legalPerson.put("address", bizMerchantInfo.getAddress()); //  详细地址
        //通用一个人
        legalPerson.put("applicant", bizMerchantInfo.getLegalPersonName()); //  联系人（固定为法人名称
        legalPerson.put("areaNo", bizMerchantInfo.getAreaNo()); //  区县代码
        legalPerson.put("cityNo", bizMerchantInfo.getCityNo()); //   城市编号
        legalPerson.put("clientServicePhoneNo", bizMerchantInfo.getClientServicePhoneNo()); //   客服电话
        legalPerson.put("contactPhoneNo", bizMerchantInfo.getContactPhoneNo()); //  联系电话
        legalPerson.put("merchantName", bizMerchantInfo.getLegalPersonName()); //  商户名称（固定格式：前缀”商户_“+法人名称）
        legalPerson.put("merchantShortHand", bizMerchantInfo.getMerchantShortHand()); //  商户简写
        legalPerson.put("provinceNo", bizMerchantInfo.getProvinceNo()); //  省份代码（调用修改时不需要传入该字段）
        legalPerson.put("bankCardAccount", bizMerchantInfo.getBankCardAccount()); //  银行账号
        legalPerson.put("bankCardHolder", bizMerchantInfo.getBankCardHolder()); //   开户名
        legalPerson.put("bankCardPhone", bizMerchantInfo.getBankCardPhone()); //  银行卡预留手机号
        legalPerson.put("bankCardPic", bizMerchantInfo.getBankCardPic()); //  银行卡照片
        legalPerson.put("bankCity", bizMerchantInfo.getBankCity()); //  开户银行城市
        legalPerson.put("bankCode", bizMerchantInfo.getBankCode()); //  银行编码
        legalPerson.put("bankProvince", bizMerchantInfo.getBankProvince()); //  开户银行省份
        legalPerson.put("bankSite", bizMerchantInfo.getBankSite()); //  开户行网点
        legalPerson.put("unionpayCode", bizMerchantInfo.getUnionpayCode()); //  开户支行联行号
        legalPerson.put("phone", bizMerchantInfo.getPhone()); //  注册手机
        String userName = IdWorker.getIdStr();
        legalPerson.put("userName", userName); //  用户名（1、唯一；每次请求都要换一个新的，因为涉及到其他部门接口，不是一个事务内2、用uuid即可）（调用修改时不需要传入该字段）
        legalPerson.put("activeAddress", bizMerchantInfo.getActiveAddress()); //  商户活体检测地址
        legalPerson.put("activeLatitude", bizMerchantInfo.getActiveLatitude()); //  	商户活体检测地址纬度
        legalPerson.put("activeLongitude", bizMerchantInfo.getActiveLongitude()); //  	商户活体检测地址经度
        legalPerson.put("registerAddress", bizMerchantInfo.getRegisterAddress()); //  商户注册地址
        legalPerson.put("registerLatitude", bizMerchantInfo.getRegisterLatitude()); //  商户注册地址纬度
        legalPerson.put("registerLongitude", bizMerchantInfo.getRegisterLongitude()); //  商户注册地址经度
        legalPerson.put("agentid", this.agentid());
        legalPerson.put("posCode", bizMerchantInfo.getPosCode());
        legalPerson.put("feeId", bizMerchantInfo.getFeeId());
        System.out.println("请求参数--》》》》" + JSONObject.toJSONString(legalPerson));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getMerchantsInfoOnline(), JSONObject.toJSONString(legalPerson));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        if (code.equals("200")) {  //成功
            JSONObject data = jsonObject.getJSONObject("data");
            String desc = data.getString("desc");
            String merchantId = data.getString("merchantId");
            String merchantNo = data.getString("merchantCode");
            System.out.println("POSP商户审核成功" + bizMerchantInfo.getLegalPersonName());
            System.out.println("POSP商户标号" + merchantNo);
            String sn = data.getString("sn");
            bizMerchantInfo.setMerchantId(merchantId);
            bizMerchantInfo.setInfoCompleted("1");
            bizMerchantInfo.setMerchantKey(data.getString("merchantKey"));
            bizMerchantInfo.setMasterKeys(data.getString("masterkeys"));
            bizMerchantInfo.setValidationValue(data.getString("validationValue"));
            bizMerchantInfo.setAcqMerId(data.getString("acqMerId"));
            bizMerchantInfo.setKhbUserId(data.getString("khbUserId"));
            bizMerchantInfo.setKhbGroupId(data.getString("khbGroupId"));
            bizMerchantInfo.setKhbAccessToken(data.getString("khbAccessToken"));
            bizMerchantInfo.setOnLine("1");
            bizMerchantInfo.setAuditStatus("3");
            bizMerchantInfo.setSn(sn);
            bizMerchantInfo.setPosCode(data.getString("posCode"));
            bizMerchantInfo.setMerchId(merchantByMerchId.getMerchId());
            bizMerchantInfo.setMerchantDesc(desc);
            bizMerchantInfo.setMerchantCode(merchantNo);
            bizMerchantInfo.setCertificateType("1");
            bizMerchantInfo.setProductType("POS");
            bizMerchantInfo.setMccCode("4812");
            bizMerchantInfo.setMerchantSubType("4");
            bizMerchantInfo.setMerchantType("1");
            bizMerchantInfo.setBankCardAccountType("1");
            bizMerchantInfo.setUserName(userName);
            bizMerchantInfo.setMerchantLevel(data.getString("merchantLevel"));
            bizMerchantInfo.setRegisterTime(DateUtils.dateFormatString(new Date()));
            bizMerchantInfo.setClientServicePhoneNo(bizMerchantInfo.getBankCardPhone());
            bizMerchantInfo.setMerchantName(bizMerchantInfo.getLegalPersonName());
            bizMerchantInfo.setRegisterAddress(bizMerchantInfo.getActiveAddress());
            bizMerchantInfo.setRegisterLatitude(bizMerchantInfo.getActiveLatitude());
            bizMerchantInfo.setRegisterLongitude(bizMerchantInfo.getActiveLongitude());
            //存到自己的库里
            boolean save = bizMerchantInfoService.save(bizMerchantInfo);
            BizPosMachine bizPosMachine=new BizPosMachine();
            bizPosMachine.setPosName("线上POS");
            bizPosMachine.setPosCode(data.getString("posCode"));
            bizPosMachine.setPosType("0");
            bizPosMachine.setPosActivateStatus("2");
            bizPosMachine.setPosBindTime(new Date());
            bizPosMachine.setPosDeposit(new BigDecimal("0"));
            bizPosMachine.setPosCashback(new BigDecimal("0"));
            bizPosMachine.setMerchId(merchantByMerchId.getMerchId());
            bizPosMachine.setCreateBy(1l);
            bizPosMachine.setCreateTime(new Date());
            bizPosMachine.setUpdateBy(1l);
            bizPosMachine.setUpdateTime(new Date());
            bizPosMachine.setVar1("");
            bizPosMachine.setVar2("");
            bizPosMachine.setVar4("");
            bizPosMachine.setVar5("0");
            bizPosMachine.setManufacturersId("0");
            bizPosMachine.setDeviceType("0");
            bizPosMachine.setModelId("0");
            bizPosMachine.setSimAmt("0");
            bizPosMachine.setSimDaynum("0");
            bizPosMachine.setChannel("5");
            posMachineService.save(bizPosMachine);

            //保存激活表数据
            BizMerchantEntry bizMerchantEntry = new BizMerchantEntry();
            bizMerchantEntry.setSn(bizMerchantInfo.getPosCode()); //sn
            bizMerchantEntry.setCertificateno(bizMerchantInfo.getCertificateNo()); //身份证号
            bizMerchantEntry.setPhone(bizMerchantInfo.getBankCardPhone());  // 预留手机号
            bizMerchantEntry.setApplicant(bizMerchantInfo.getLegalPersonName()); // 姓名
            bizMerchantEntry.setMerchantNo(bizMerchantInfo.getMerchantCode()); // 姓名
            //激活表插入数据
            int ok = recordsService.snRecordsOneVersion(bizMerchantEntry);
            //推送审核成功消息
            String fanXianMess = "SN：" + bizMerchantInfo.getPosCode() + "正在审核";
            BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
            fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
            fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
            fanXianMessageRecords.setReadStatus(0); // 消息未读
            fanXianMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
            return AjaxResult.success();
        } else {
            String fanXianMess = "SN：" + bizMerchantInfo.getPosCode() + "审核失败"+msg;
            if (jsonObject.containsKey("data")){
                JSONObject data = jsonObject.getJSONObject("data");
                String desc = data.getString("desc");
                //推送审核成功消息
                fanXianMess = fanXianMess+desc;
            }
            //推送审核成功消息
            BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
            fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
            fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
            fanXianMessageRecords.setReadStatus(0); // 消息未读
            fanXianMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
            return AjaxResult.error(msg);
        }

    }
    @Override
    public List<BizMercahntFeeNameDTO> echoFeeIdOnline() {
        return bizMerchantInfoMapper.echoFeeIdOnline();
    }
    public JSONObject onlineBinding(BizMerchantInfo bizMerchantInfo) {
        JSONObject erro = new JSONObject();
        if(null!=bizMerchantInfo){
            if("1".equals(bizMerchantInfo.getActiveStatus())){
                //查询商户信息
                BizMerchantInfo info=bizMerchantInfoMapper.getInfoByMerchantCode(bizMerchantInfo.getMerchantCode());
                //查询设备激活表信息
                BizPosMachineStatusRecords dto=recordsService.selectBizPosMachineStatusRecordsBysnCode(info.getPosCode());
                if(null!=dto){
                    if("2".equals(dto.getRecordsType())){
                        System.out.println("已存在激活数据"+info.getPosCode());
                        erro.put("code", 500);
                        erro.put("msg", "已存在激活数据");
                        return erro;
                    }else{
                        System.out.println("设备号："+info.getPosCode());
                        //更新状态为激活
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        dto.setActiveTime(df.format(new Date()));
                        dto.setRecordsType("2");
                        dto.setSnCode(info.getPosCode());
                        machineStatusRecordsMapper.updateBizPosRecords(dto);
                        bizPosMachineMapper.updatePosPosMachine(info.getPosCode());
                        bizPosMachineMapper.generateAllPosMerchantRelatedProcedure();// 运行函数
                    }
                }else{
                    System.out.println("未查询到设备激活表数据"+info.getPosCode());
                    erro.put("code", 500);
                    erro.put("msg", "未查询到设备激活表数据");
                    return erro;
                }

            }
            erro.put("code", 200);
            erro.put("msg", "接收成功");
            return erro;
        }
        erro.put("code", 500);
        erro.put("msg", "接收失败");
        return erro;
    }
    @Override
    public JSONObject updateSettleAccountOnline(BizMerchantInfo merchantInfo) {
        JSONObject legalPerson = new JSONObject();
        //修改
        if ("".equals(merchantInfo.getMerchantCode()) && merchantInfo.getMerchantCode() == null) {
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "商户编号不能为空");
            return erro;
        }
        BizMerchantInfo bizMerchantInfo = bizMerchantInfoService.getMerchantInfo(merchantInfo);
        if(!"3".equals(bizMerchantInfo.getAuditStatus()) &&
                !"1".equals(bizMerchantInfo.getSettleAccountStatus())
                && !"3".equals(bizMerchantInfo.getSettleAccountStatus())){
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", "修改结算卡中,请勿再次修改");
            return erro;
        }
        bizMerchantInfo.setBankCardPic(merchantInfo.getBankCardPic()); // 银行卡照片
        bizMerchantInfo.setBankCardAccount(merchantInfo.getBankCardAccount()); //银行卡号
        bizMerchantInfo.setBankCardHolder(merchantInfo.getBankCardHolder()); // 开户名
        bizMerchantInfo.setBankCardPhone(merchantInfo.getBankCardPhone()); // 预留手机好
        bizMerchantInfo.setBankCode(merchantInfo.getBankCode()); // 银行编码
        bizMerchantInfo.setBankSite(merchantInfo.getBankSite()); // 网点
        legalPerson.put("merchantCode", bizMerchantInfo.getMerchantCode());
        legalPerson.put("certificateEndDate", bizMerchantInfo.getCertificateEndDate()); //  证件有效期截止日期（例：1949-10-01）;
        legalPerson.put("certificateNo", bizMerchantInfo.getCertificateNo());   //  法人证件号码
        legalPerson.put("certificateStartDate", bizMerchantInfo.getCertificateStartDate()); //  证件有效期开始日期（例：1949-10-01）
        legalPerson.put("certificatesBackPic", bizMerchantInfo.getCertificatesBackPic()); //  证件国徽面
        legalPerson.put("certificatesFrontPic", bizMerchantInfo.getCertificatesFrontPic()); //  证件人脸面
        legalPerson.put("idcardHandPic", bizMerchantInfo.getIdcardHandPic()); //  手持身份证照片（与法人人脸识别留存照片两者必须有一个不为空）; 例如:picture2/手持身份证照片.jpg
        legalPerson.put("legalPersonName", bizMerchantInfo.getLegalPersonName()); //  法人姓名
        legalPerson.put("address", bizMerchantInfo.getAddress()); //  详细地址
        //通用一个人
        legalPerson.put("applicant", bizMerchantInfo.getLegalPersonName()); //  联系人（固定为法人名称
        legalPerson.put("areaNo", bizMerchantInfo.getAreaNo()); //  区县代码
        legalPerson.put("cityNo", bizMerchantInfo.getCityNo()); //   城市编号
        legalPerson.put("clientServicePhoneNo", bizMerchantInfo.getClientServicePhoneNo()); //   客服电话
        legalPerson.put("contactPhoneNo", bizMerchantInfo.getContactPhoneNo()); //  联系电话
        legalPerson.put("merchantName", bizMerchantInfo.getLegalPersonName()); //  商户名称（固定格式：前缀”商户_“+法人名称）
        legalPerson.put("merchantShortHand", bizMerchantInfo.getMerchantShortHand()); //  商户简写
        legalPerson.put("provinceNo", bizMerchantInfo.getProvinceNo()); //  省份代码（调用修改时不需要传入该字段）
        JSONObject settleAccountInfo = new JSONObject();
        legalPerson.put("bankCardAccount", bizMerchantInfo.getBankCardAccount()); //  银行账号
        legalPerson.put("bankCardHolder", bizMerchantInfo.getBankCardHolder()); //   开户名
        legalPerson.put("bankCardPhone", bizMerchantInfo.getBankCardPhone()); //  银行卡预留手机号
        legalPerson.put("bankCardPic", bizMerchantInfo.getBankCardPic()); //  银行卡照片
        legalPerson.put("bankCity", bizMerchantInfo.getBankCity()); //  开户银行城市
        legalPerson.put("bankCode", bizMerchantInfo.getBankCode()); //  银行编码
        legalPerson.put("bankProvince", bizMerchantInfo.getBankProvince()); //  开户银行省份
        legalPerson.put("bankSite", bizMerchantInfo.getBankSite()); //  开户行网点
        legalPerson.put("unionpayCode", bizMerchantInfo.getUnionpayCode()); //  开户支行联行号
        legalPerson.put("phone", bizMerchantInfo.getPhone()); //  注册手机
        String userName = IdWorker.getIdStr();
        legalPerson.put("userName", userName); //  用户名（1、唯一；每次请求都要换一个新的，因为涉及到其他部门接口，不是一个事务内2、用uuid即可）（调用修改时不需要传入该字段）
        legalPerson.put("activeAddress", bizMerchantInfo.getActiveAddress()); //  商户活体检测地址
        legalPerson.put("activeLatitude", bizMerchantInfo.getActiveLatitude()); //  	商户活体检测地址纬度
        legalPerson.put("activeLongitude", bizMerchantInfo.getActiveLongitude()); //  	商户活体检测地址经度
        legalPerson.put("registerAddress", bizMerchantInfo.getRegisterAddress()); //  商户注册地址
        legalPerson.put("registerLatitude", bizMerchantInfo.getRegisterLatitude()); //  商户注册地址纬度
        legalPerson.put("registerLongitude", bizMerchantInfo.getRegisterLongitude()); //  商户注册地址经度
        legalPerson.put("agentid", this.getAgentid(bizMerchantInfo.getPosCode()));
        legalPerson.put("posCode", bizMerchantInfo.getPosCode());
        //把结算卡状态修改为  进行中
        bizMerchantInfoMapper.updateSettleAccountStatus(bizMerchantInfo.getMerchantCode());
        System.out.println("请求参数--》》》》" + JSONObject.toJSONString(legalPerson));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getUpdateSettleAccountOnline(), JSONObject.toJSONString(legalPerson));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if (code.equals("200")) {  //成功
            JSONObject data = jsonObject.getJSONObject("data");
            BizMerchantInfo bizMerchantInfo1 = new BizMerchantInfo();
            bizMerchantInfo1.setMerchantCode(bizMerchantInfo.getMerchantCode());

            //审核成功 更新审核提示
            bizMerchantInfo.setUpdateTime(new Date());
            bizMerchantInfo.setSettleAccountStatus("3");
            //更新自己的库
            bizMerchantInfoService.updateMerchantsInfoByMerchantCode(bizMerchantInfo);

            return jsonObject;
        } else {
            JSONObject erro = new JSONObject();
            erro.put("code", 500);
            erro.put("msg", jsonObject.getString("msg"));
            return erro;
        }
    }
    @Override
    @Transactional
    public AjaxResult addMerchantsQbInfo(BizMerchantInfo bizMerchantInfo) {
        JSONObject legalPerson = new JSONObject();
        String posCode = bizMerchantInfoMapper.selectMerchantInfoSn(bizMerchantInfo.getPosCode());
        if (StringUtils.isNotBlank(posCode)) {

            return AjaxResult.error("已存在商户");
        }
        BizPosMachine posMachineBySnCode = posMachineService.getPosMachineBySnCode(bizMerchantInfo.getPosCode());
        if (posMachineBySnCode == null) {
            return AjaxResult.error("设备不存在");
        }
        if(null==bizMerchantInfo.getFeeId()){//前端传值就用前端传的，不传就默认0.6
            //设置默认费率为0.6
            bizMerchantInfo.setFeeId(DEFAULT_FEE_ID);
        }
        // 代理
        BizMerchant merchantByMerchId = bizMerchantService.getMerchantByMerchId(posMachineBySnCode.getMerchId());
        String certificateEndDate="";
        if(bizMerchantInfo.getCertificateEndDate().equals("长期")){
            certificateEndDate=bizMerchantInfo.getCertificateEndDate();
        }else{
            certificateEndDate=bizMerchantInfo.getCertificateEndDate().replace(".","");
            certificateEndDate=certificateEndDate.replaceAll("-","");
            certificateEndDate=certificateEndDate.replace("年","");
            certificateEndDate=certificateEndDate.replace("月","");
            certificateEndDate=certificateEndDate.replace("日","");
            certificateEndDate=DateUtils.dateConvertion(certificateEndDate);
        }

        String certificateStartDate=bizMerchantInfo.getCertificateStartDate().replace(".","");
        certificateStartDate=certificateStartDate.replaceAll("-","");
        certificateStartDate=certificateStartDate.replace("年","");
        certificateStartDate=certificateStartDate.replace("月","");
        certificateStartDate=certificateStartDate.replace("日","");
        certificateStartDate=DateUtils.dateConvertion(certificateStartDate);
        legalPerson.put("certificateEndDate", certificateEndDate); //  证件有效期截止日期（例：1949-10-01）;
        legalPerson.put("certificateNo", bizMerchantInfo.getCertificateNo());   //  法人证件号码
        legalPerson.put("certificateStartDate", certificateStartDate); //  证件有效期开始日期（例：1949-10-01）
        //暂时写死
        legalPerson.put("certificatesBackPic", bizMerchantInfo.getCertificatesBackPic()); //  证件国徽面
        legalPerson.put("certificatesFrontPic", bizMerchantInfo.getCertificatesFrontPic()); //  证件人脸面
        legalPerson.put("idcardHandPic", bizMerchantInfo.getIdcardHandPic()); //  手持身份证照片（与法人人脸识别留存照片两者必须有一个不为空）; 例如:picture2/手持身份证照片.jpg
        legalPerson.put("legalPersonName", bizMerchantInfo.getLegalPersonName()); //  法人姓名
        legalPerson.put("address", bizMerchantInfo.getAddress()); //  详细地址
        //通用一个人
        legalPerson.put("applicant", bizMerchantInfo.getLegalPersonName()); //  联系人（固定为法人名称
        legalPerson.put("areaNo", bizMerchantInfo.getAreaNo()); //  区县代码
        legalPerson.put("cityNo", bizMerchantInfo.getCityNo()); //   城市编号
        legalPerson.put("clientServicePhoneNo", bizMerchantInfo.getClientServicePhoneNo()); //   客服电话
        legalPerson.put("contactPhoneNo", bizMerchantInfo.getContactPhoneNo()); //  联系电话
        legalPerson.put("merchantName", bizMerchantInfo.getLegalPersonName()); //  商户名称（固定格式：前缀”商户_“+法人名称）
        legalPerson.put("merchantShortHand", bizMerchantInfo.getMerchantShortHand()); //  商户简写
        legalPerson.put("provinceNo", bizMerchantInfo.getProvinceNo()); //  省份代码（调用修改时不需要传入该字段）
        legalPerson.put("bankCardAccount", bizMerchantInfo.getBankCardAccount()); //  银行账号
        legalPerson.put("bankCardHolder", bizMerchantInfo.getBankCardHolder()); //   开户名
        legalPerson.put("bankCardPhone", bizMerchantInfo.getBankCardPhone()); //  银行卡预留手机号
        legalPerson.put("bankCardPic", bizMerchantInfo.getBankCardPic()); //  银行卡照片
        legalPerson.put("bankCity", bizMerchantInfo.getBankCity()); //  开户银行城市
        legalPerson.put("bankCode", bizMerchantInfo.getBankCode()); //  银行编码
        legalPerson.put("bankProvince", bizMerchantInfo.getBankProvince()); //  开户银行省份
        legalPerson.put("bankSite", bizMerchantInfo.getBankSite()); //  开户行网点
        legalPerson.put("unionpayCode", bizMerchantInfo.getUnionpayCode()); //  开户支行联行号
        legalPerson.put("phone", bizMerchantInfo.getPhone()); //  注册手机
        String userName = IdWorker.getIdStr();
        legalPerson.put("userName", userName); //  用户名（1、唯一；每次请求都要换一个新的，因为涉及到其他部门接口，不是一个事务内2、用uuid即可）（调用修改时不需要传入该字段）
        legalPerson.put("activeAddress", bizMerchantInfo.getActiveAddress()); //  商户活体检测地址
        legalPerson.put("activeLatitude", bizMerchantInfo.getActiveLatitude()); //  	商户活体检测地址纬度
        legalPerson.put("activeLongitude", bizMerchantInfo.getActiveLongitude()); //  	商户活体检测地址经度
        legalPerson.put("registerAddress", bizMerchantInfo.getRegisterAddress()); //  商户注册地址
        legalPerson.put("registerLatitude", bizMerchantInfo.getRegisterLatitude()); //  商户注册地址纬度
        legalPerson.put("registerLongitude", bizMerchantInfo.getRegisterLongitude()); //  商户注册地址经度
        String img=bizMerchantInfo.getImg();
        legalPerson.put("qbFaceRecognition", img.substring(img.indexOf(",")+1)); //  图片bas64
        legalPerson.put("agentid", this.agentid());
        legalPerson.put("posCode", bizMerchantInfo.getPosCode());
        legalPerson.put("feeId", bizMerchantInfo.getFeeId());
        System.out.println("请求参数--》》》》" + JSONObject.toJSONString(legalPerson));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getMerchantsQbInfo(), JSONObject.toJSONString(legalPerson));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        if (code.equals("200")) {  //成功
            JSONObject data = jsonObject.getJSONObject("data");
            String desc = data.getString("desc");
            String merchantId = data.getString("merchantId");
            String merchantNo = data.getString("merchantCode");
            System.out.println("POSP商户审核成功" + bizMerchantInfo.getLegalPersonName());
            System.out.println("POSP商户标号" + merchantNo);
            String sn = data.getString("sn");
            bizMerchantInfo.setMerchantId(merchantId);
            bizMerchantInfo.setInfoCompleted("0");
            bizMerchantInfo.setMerchantKey(data.getString("merchantKey"));
            bizMerchantInfo.setMasterKeys(data.getString("masterkeys"));
            bizMerchantInfo.setValidationValue(data.getString("validationValue"));
            bizMerchantInfo.setAcqMerId("");
            bizMerchantInfo.setOnLine("0");
            bizMerchantInfo.setAuditStatus(data.getString("auditStatus"));
            bizMerchantInfo.setSn(sn);
            bizMerchantInfo.setMerchId(posMachineBySnCode.getMerchId());
            bizMerchantInfo.setMerchantDesc(desc);
            bizMerchantInfo.setMerchantCode(merchantNo);
            bizMerchantInfo.setCertificateType("1");
            bizMerchantInfo.setProductType("POS");
            bizMerchantInfo.setMccCode("4812");
            bizMerchantInfo.setMerchantSubType("4");
            bizMerchantInfo.setMerchantType("1");
            bizMerchantInfo.setBankCardAccountType("1");
            bizMerchantInfo.setUserName(userName);
            bizMerchantInfo.setMerchantLevel(data.getString("merchantLevel"));
            bizMerchantInfo.setRegisterTime(DateUtils.dateFormatString(new Date()));
            bizMerchantInfo.setClientServicePhoneNo(bizMerchantInfo.getBankCardPhone());
            bizMerchantInfo.setMerchantName(bizMerchantInfo.getLegalPersonName());
            bizMerchantInfo.setRegisterAddress(bizMerchantInfo.getActiveAddress());
            bizMerchantInfo.setRegisterLatitude(bizMerchantInfo.getActiveLatitude());
            bizMerchantInfo.setRegisterLongitude(bizMerchantInfo.getActiveLongitude());
            //存到自己的库里
            boolean save = bizMerchantInfoService.save(bizMerchantInfo);
            //推送审核成功消息
            String fanXianMess = "SN：" + bizMerchantInfo.getPosCode() + "正在审核";
            BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
            fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
            fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
            fanXianMessageRecords.setReadStatus(0); // 消息未读
            fanXianMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
            return AjaxResult.success();
        } else {
            String fanXianMess = "SN：" + bizMerchantInfo.getPosCode() + "审核失败"+msg;
            if (jsonObject.containsKey("data")){
                JSONObject data = jsonObject.getJSONObject("data");
                String desc = data.getString("desc");
                //推送审核成功消息
                fanXianMess = fanXianMess+desc;
            }
            //推送审核成功消息
            BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
            fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
            fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
            fanXianMessageRecords.setReadStatus(0); // 消息未读
            fanXianMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
            return AjaxResult.error(msg);
        }

    }
    public String getAgentid(String posCode){
        return bizPosMachineMapper.selectAgentid(posCode);
    }
    @Override
    public String hybAddInfo(JSONObject paramsObj){
        String hrtMid=paramsObj.getString("hrtMid");//商户号
        String sn=paramsObj.getString("sn");//设备号
        String regDate=paramsObj.getString("regDate");//日期
        String rebateType=paramsObj.getString("rebateType");//活动类型
        String tname=paramsObj.getString("tname");//商户名称
        bizMerchantInfoMapper.deleteBySN(sn);
        //删除激活表信息
        bizPosMachineStatusRecordsMapper.deleteBizPosRecordsNew(sn);
        //更新设备表激活状态
        bizPosMachineStatusRecordsMapper.updatePosMachine(sn);
        //查询设备信息
        BizPosMachine machine=posMachineService.selectPosBySnCode(sn);
        BizMerchantInfo bizMerchantInfo=new BizMerchantInfo();
        bizMerchantInfo.setInfoCompleted("1");
        bizMerchantInfo.setAuditStatus("3");
        bizMerchantInfo.setPosCode(sn);
        bizMerchantInfo.setMerchantName(tname);
        bizMerchantInfo.setMerchantShortHand(tname);
        bizMerchantInfo.setLegalPersonName(tname);
        bizMerchantInfo.setMerchId(machine.getMerchId());
        bizMerchantInfo.setMerchantCode(hrtMid);
        bizMerchantInfo.setRegisterTime(regDate);
        bizMerchantInfo.setWhetherBinding("1");
        bizMerchantInfo.setOnLine("0");
        //存到自己的库里
        boolean save = bizMerchantInfoService.save(bizMerchantInfo);
        //保存激活表数据
        BizMerchantEntry bizMerchantEntry = new BizMerchantEntry();
        bizMerchantEntry.setSn(bizMerchantInfo.getPosCode()); //sn
        bizMerchantEntry.setCertificateno(bizMerchantInfo.getCertificateNo()); //身份证号
        bizMerchantEntry.setPhone(bizMerchantInfo.getBankCardPhone());  // 预留手机号
        bizMerchantEntry.setApplicant(bizMerchantInfo.getLegalPersonName()); // 姓名
        bizMerchantEntry.setMerchantNo(bizMerchantInfo.getMerchantCode()); // 姓名
        //激活表插入数据
        int ok = recordsService.snRecordsOneVersion(bizMerchantEntry);
        return null;
    }

    @Override
    public void deleteBySN(String posSn) {
        bizMerchantInfoMapper.deleteBySN(posSn);
    }
    @Override
    public AjaxResult queryKDBUpper(BizMerchantInfo bizMerchantInfo) {
        System.out.println("开店宝查询接口接收参数为："+bizMerchantInfo);
        JSONObject legalPerson = new JSONObject();
        legalPerson.put("merchantCode",bizMerchantInfo.getMerchantCode());
        System.out.println("请求参数--》》》》" + JSONObject.toJSONString(legalPerson));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getQueryKDBUpper(), JSONObject.toJSONString(legalPerson));
        JSONObject obj=JSONObject.parseObject(result);
        String code=obj.getString("code");
        String msg=obj.getString("msg");
        if("500".equals(code)){
            AjaxResult ajaxResult=AjaxResult.error(msg);
            return ajaxResult;
        }else {
            AjaxResult ajaxResult=AjaxResult.success("请求成功");
            JSONArray list=obj.getJSONArray("data");
            ajaxResult.put("data",list);
            return ajaxResult;
        }
    }


    @Override
    public List<BizMerchantInfo> getCupsNameList(String idCard) {
        return bizMerchantInfoMapper.getCupsNameList(idCard);
    }


    @Override
    public List<BizMerchantInfo> getMerchantInfoList(String idCard) {
        return bizMerchantInfoMapper.getMerchantInfoList(idCard);
    }

    @Override
    public AjaxResult changeCupsName(String json){
        Map<String,String> map = HttpUtil.generateMap(json);
        String oldMerchantCode = map.get("oldMerchantCode");
        String newMerchantCOde = map.get("newMerchantCode");
        BizMerchantInfo bizMerchantInfo = bizMerchantInfoMapper.getMerchantInfoByMerchantCode(oldMerchantCode);
        if(bizMerchantInfo.getBusNature().equals("3")){
            bizMerchantInfo.setXwSigning("1");
        }else{
            bizMerchantInfo.setQySigning("1");
        }
        this.saveOrUpdate(bizMerchantInfo);// 标记是否是企业或小微
        String posCode = bizMerchantInfo.getPosCode();
        String res = unbind(bizMerchantInfo); // 解绑
        if("true".equals(res)){
            //去绑定
            BindPosDto bindPosDto = new BindPosDto();
            bindPosDto.setPosCode(posCode);
            bindPosDto.setMerchantNo(newMerchantCOde);
            String resB = bind(bindPosDto);
            if("true".equals(resB)){
                return AjaxResult.success("切换成功");
            }else{
                return AjaxResult.error(resB);
            }
        }else{
            return AjaxResult.error(res);
        }

    }


    public String  unbind(BizMerchantInfo bizMerchantInfo){
        JSONObject param = new JSONObject();
        param.put("posCode", bizMerchantInfo.getPosCode());
        param.put("merchantNo", bizMerchantInfo.getMerchantCode());
        param.put("appletSignature", "xcx");
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getUnbind(), JSONObject.toJSONString(param));
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");
        String msg = jsonObject.getString("msg");
        //查询是否有报件信息
        if (code == 200) {
            //解绑
            relieve(bizMerchantInfo.getPosCode());
            return "true";
        }
        return msg;
    }


    public String bind(BindPosDto bindPosDto) {
        BizPosMachine posMachineBySnCode = posMachineService.getPosMachineBySnCode(bindPosDto.getPosCode());
        if (posMachineBySnCode == null) {
            return "无此设备";
        }
        JSONObject param = new JSONObject();
        param.put("posType", "2");   // 2无押
        param.put("merchantNo", bindPosDto.getMerchantNo());
        param.put("posCode", bindPosDto.getPosCode());
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getBindingPosCodeNoSF(), JSONObject.toJSONString(param));
        JSONObject paramObject = JSONObject.parseObject(result);
        if (paramObject.getInteger("code") == 200) {
            posMachineService.updatePosPosMachineActivateStatusBySn(bindPosDto.getPosCode());
            bizMerchantInfoMapper.updateMercahntInfoWhetherBinding(bindPosDto.getMerchantNo(), bindPosDto.getPosCode());
            BizMerchantInfo Info = new BizMerchantInfo();
            Info.setMerchantCode(bindPosDto.getMerchantNo());
            BizMerchantInfo bizMerchantInfo = bizMerchantInfoMapper.getMerchantInfo(Info);
            BizPosMachine bizPosMachine = posMachineService.selectPosBySnCode(bindPosDto.getPosCode());
            BizMerchantEntry bizMerchantEntry = new BizMerchantEntry();
            bizMerchantEntry.setSn(bizMerchantInfo.getPosCode()); //sn
            bizMerchantEntry.setCertificateno(bizMerchantInfo.getCertificateNo()); //身份证号
            bizMerchantEntry.setPhone(bizMerchantInfo.getBankCardPhone());  // 预留手机号
            bizMerchantEntry.setApplicant(bizMerchantInfo.getLegalPersonName()); // 姓名
            bizMerchantEntry.setMerchantNo(bizMerchantInfo.getMerchantCode()); // 姓名
            bizMerchantEntry.setTerminalCode(bizPosMachine.getPosType()); // 姓名
            //激活表插入数据
            int ok = recordsService.snRecordsOneVersion(bizMerchantEntry);
            //更新设备表绑定状态
            System.out.println("绑定成功" + bindPosDto.getPosCode() + DateUtils.dateFormatString(new Date()));
            return "true";
        } else {
            return paramObject.getString("msg");
        }
    }


    @Override
    public  AjaxResult excuteSubmitNewMerchant(String json){
        Map<String , String> map = PublicUtil.generateMap(json);
        String merchantShortHand = map.get("merchantShortHand");
        String busRegNo = map.get("busRegNo");
        String merchantCode = map.get("merchantCode");
        BizMerchantInfo bizMerchantInfo = bizMerchantInfoMapper.getInfoByMerchantCode(merchantCode);
        bizMerchantInfo.setMerchantCode(null);
        bizMerchantInfo.setPosCode(null);
        bizMerchantInfo.setMerchantShortHand(merchantShortHand);
        bizMerchantInfo.setBusRegNo(busRegNo);
        bizMerchantInfo.setBusiLicenseImg(map.get("busiLicenseImg"));
        bizMerchantInfo.setBusiDoorImg(map.get("busiDoorImg"));
        bizMerchantInfo.setCashDeskImg(map.get("cashDeskImg"));
        bizMerchantInfo.setBusiPlaceImg(map.get("busiPlaceImg"));
        bizMerchantInfo.setBusRegStartDt(map.get("busRegStartDt"));
        bizMerchantInfo.setBusRegEndDt(map.get("busRegEndDt"));
        bizMerchantInfo.setLegalpersonIsSett("N");
        bizMerchantInfo.setSettAccMark("1");
        bizMerchantInfo.setBusNature("2");
        bizMerchantInfo.setMccCd(map.get("mccCd"));
        return addMerchantsKDBInfoForWeb(bizMerchantInfo);

    }
    @Override
    public  AjaxResult excuteSubmitNewXwMerchant(String json){
        Map<String , String> map = PublicUtil.generateMap(json);
        String merchantCode = map.get("merchantCode");
        BizMerchantInfo bizMerchantInfo = bizMerchantInfoMapper.getInfoByMerchantCode(merchantCode);
        bizMerchantInfo.setMerchantCode(null);
        bizMerchantInfo.setPosCode(null);
        return addMerchantsKDBInfoForWeb(bizMerchantInfo);
    }

    public AjaxResult addMerchantsKDBInfoForWeb(BizMerchantInfo bizMerchantInfo) {
        JSONObject legalPerson = new JSONObject();
        // 代理
        BizMerchant merchantByMerchId = bizMerchantService.getMerchantByMerchId(bizMerchantInfo.getMerchId());
        legalPerson.put("certificateEndDate", bizMerchantInfo.getCertificateEndDate()); //  证件有效期截止日期（例：1949-10-01）;
        legalPerson.put("certificateNo", bizMerchantInfo.getCertificateNo());   //  法人证件号码
        legalPerson.put("certificateStartDate", bizMerchantInfo.getCertificateStartDate()); //  证件有效期开始日期（例：1949-10-01）
        legalPerson.put("certificatesBackPic", bizMerchantInfo.getCertificatesBackPic()); //  证件国徽面
        legalPerson.put("certificatesFrontPic", bizMerchantInfo.getCertificatesFrontPic()); //  证件人脸面
        legalPerson.put("idcardHandPic", bizMerchantInfo.getIdcardHandPic()); //  手持身份证照片（与法人人脸识别留存照片两者必须有一个不为空）; 例如:picture2/手持身份证照片.jpg
        legalPerson.put("legalPersonName", bizMerchantInfo.getLegalPersonName()); //  法人姓名
        legalPerson.put("address", bizMerchantInfo.getAddress()); //  详细地址
        //通用一个人
        legalPerson.put("applicant", bizMerchantInfo.getLegalPersonName()); //  联系人（固定为法人名称
        legalPerson.put("areaNo", bizMerchantInfo.getAreaNo()); //  区县代码
        legalPerson.put("cityNo", bizMerchantInfo.getCityNo()); //   城市编号
        legalPerson.put("provinceName", bizMerchantInfo.getProvinceName()); //   城市编号
        legalPerson.put("cityName", bizMerchantInfo.getCityName()); //   城市编号
        legalPerson.put("areaName", bizMerchantInfo.getAreaName()); //   城市编号
        legalPerson.put("clientServicePhoneNo", bizMerchantInfo.getClientServicePhoneNo()); //   客服电话
        legalPerson.put("contactPhoneNo", bizMerchantInfo.getContactPhoneNo()); //  联系电话
        legalPerson.put("merchantName", bizMerchantInfo.getLegalPersonName()); //  商户名称（固定格式：前缀”商户_“+法人名称）
        legalPerson.put("merchantShortHand", bizMerchantInfo.getMerchantShortHand()); //  商户简写
        legalPerson.put("provinceNo", bizMerchantInfo.getProvinceNo()); //  省份代码（调用修改时不需要传入该字段）
        legalPerson.put("bankCardAccount", bizMerchantInfo.getBankCardAccount()); //  银行账号
        JSONObject cardNo=new JSONObject();
        cardNo.put("cardNo",bizMerchantInfo.getBankCardAccount());
        String result22 = HttpUtil.doPostxxl(PosPCommonParamConfig.getObtainBank(), JSONObject.toJSONString(cardNo));
        if(StringUtil.isNotEmpty(result22)) {
            JSONObject jsonResult = JSONObject.parseObject(result22);
            if ("200".equals(jsonResult.getString("code"))) {
                legalPerson.put("bankName", jsonResult.getString("data"));
            }else{
                System.out.println(bizMerchantInfo.getBankCardAccount()+"小程序企业入网签约未查询到开户行");
                return AjaxResult.error("请核对银行卡号");
            }
        }
        legalPerson.put("bankCardHolder", bizMerchantInfo.getBankCardHolder()); //   开户名
        legalPerson.put("bankCardPhone", bizMerchantInfo.getBankCardPhone()); //  银行卡预留手机号
        legalPerson.put("bankCardPic", bizMerchantInfo.getBankCardPic()); //  银行卡照片
        legalPerson.put("bankCity", bizMerchantInfo.getBankCity()); //  开户银行城市
        legalPerson.put("bankCode", bizMerchantInfo.getBankCode()); //  银行编码
        legalPerson.put("bankProvince", bizMerchantInfo.getBankProvince()); //  开户银行省份
        legalPerson.put("bankSite", bizMerchantInfo.getBankSite()); //  开户行网点
        legalPerson.put("unionpayCode", bizMerchantInfo.getUnionpayCode()); //  开户支行联行号
        legalPerson.put("phone", bizMerchantInfo.getPhone()); //  注册手机
        String userName = IdWorker.getIdStr();
        legalPerson.put("userName", userName); //  用户名（1、唯一；每次请求都要换一个新的，因为涉及到其他部门接口，不是一个事务内2、用uuid即可）（调用修改时不需要传入该字段）
        legalPerson.put("activeAddress", bizMerchantInfo.getActiveAddress()); //  商户活体检测地址
        legalPerson.put("activeLatitude", bizMerchantInfo.getActiveLatitude()); //  	商户活体检测地址纬度
        legalPerson.put("activeLongitude", bizMerchantInfo.getActiveLongitude()); //  	商户活体检测地址经度
        legalPerson.put("registerAddress", bizMerchantInfo.getRegisterAddress()); //  商户注册地址
        legalPerson.put("registerLatitude", bizMerchantInfo.getRegisterLatitude()); //  商户注册地址纬度
        legalPerson.put("registerLongitude", bizMerchantInfo.getRegisterLongitude()); //  商户注册地址经度
        BizMerchant bizMerchant = bizMerchantService.getMerchantByMerchId(bizMerchantInfo.getMerchId());
        String deptId = bizMicroInfoService.getDeptIdByuserId(bizMerchant.getUserId().toString());
        String agentId ;
        if("117".equals(deptId)){
            agentId = "NVKXVIM6";
        }else if("118".equals(deptId)){
            agentId = "ATISQM34";
        }else{
            agentId = "CNFSNHVU";
        }
        legalPerson.put("agentid", agentId);
        legalPerson.put("posCode", bizMerchantInfo.getPosCode());
        legalPerson.put("feeId", bizMerchantInfo.getFeeId());
        legalPerson.put("faceAuthFlag", bizMerchantInfo.getFaceAuthFlag());
        legalPerson.put("faceAuthOrderNo", bizMerchantInfo.getFaceAuthOrderNo());
        //企业进件20240116新增
        legalPerson.put("settAccMark", bizMerchantInfo.getSettAccMark());
        legalPerson.put("busNature", bizMerchantInfo.getBusNature());
        legalPerson.put("busRegNo", bizMerchantInfo.getBusRegNo());
        legalPerson.put("busRegType", bizMerchantInfo.getBusRegType());
        legalPerson.put("receiptProImg", bizMerchantInfo.getReceiptProImg());
        legalPerson.put("busiLicenseImg", bizMerchantInfo.getBusiLicenseImg());
        legalPerson.put("cashDeskImg", bizMerchantInfo.getCashDeskImg());
        legalPerson.put("busiPlaceImg", bizMerchantInfo.getBusiPlaceImg());
        legalPerson.put("busiDoorImg", bizMerchantInfo.getBusiDoorImg());
        legalPerson.put("bankAboveImg", bizMerchantInfo.getBankAboveImg());
        legalPerson.put("settleProImg", bizMerchantInfo.getSettleProImg());
        legalPerson.put("otherImg1", bizMerchantInfo.getOtherImg1());
        legalPerson.put("busRegStartDt", bizMerchantInfo.getBusRegStartDt());
        legalPerson.put("busRegEndDt", bizMerchantInfo.getBusRegEndDt());
        legalPerson.put("legalpersonIsSett", bizMerchantInfo.getLegalpersonIsSett());
        legalPerson.put("settCrpNo", bizMerchantInfo.getSettCrpNo());
        legalPerson.put("settCrpAboveImg", bizMerchantInfo.getSettCrpAboveImg());
        legalPerson.put("settCrpBelovImg", bizMerchantInfo.getSettCrpBelovImg());
        legalPerson.put("nonCrpNmSettleProImg", bizMerchantInfo.getNonCrpNmSettleProImg());
        legalPerson.put("mercTypeMCC", bizMerchantInfo.getMccCd());

        legalPerson.put("reqNo", bizMerchantInfo.getReqNo());
        System.out.println(bizMerchantInfo.getCertificateNo()+"小程序无SN进件请求参数" + JSONObject.toJSONString(legalPerson));
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getMerchantsKDBInfoNoSn(), JSONObject.toJSONString(legalPerson));
        System.out.println(bizMerchantInfo.getCertificateNo()+"小程序无SN进件返回参数" + JSONObject.toJSONString(legalPerson));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        JSONObject data = jsonObject.getJSONObject("data");
        String desc="";
        if(data!=null){
            desc = data.getString("desc");
        }else{
            desc=msg;
        }
        if (code.equals("200")) {  //成功
            String merchantId = data.getString("merchantId");
            String merchantNo = data.getString("merchantNo");
            bizMerchantInfo.setInfoCompleted("0");
            bizMerchantInfo.setMerchantId(merchantId);
            bizMerchantInfo.setMerchantKey(data.getString("merchantKey"));
            bizMerchantInfo.setMasterKeys(data.getString("masterkeys"));
            bizMerchantInfo.setValidationValue(data.getString("validationValue"));
            bizMerchantInfo.setAuditStatus("2");
            bizMerchantInfo.setMerchId(bizMerchantInfo.getMerchId());
            bizMerchantInfo.setMerchantDesc(desc);
            bizMerchantInfo.setMerchantCode(merchantNo);
            bizMerchantInfo.setCertificateType("1");
            bizMerchantInfo.setProductType("POS");
            bizMerchantInfo.setMccCode(bizMerchantInfo.getMccCd());
            bizMerchantInfo.setMerchantSubType("4");
            bizMerchantInfo.setMerchantType("1");
            bizMerchantInfo.setBankCardAccountType("1");
            bizMerchantInfo.setUserName(userName);
            bizMerchantInfo.setMerchantLevel(data.getString("merchantLevel"));
            bizMerchantInfo.setRegisterTime(DateUtils.dateFormatString(new Date()));
            bizMerchantInfo.setClientServicePhoneNo(bizMerchantInfo.getBankCardPhone());
            bizMerchantInfo.setMerchantName(bizMerchantInfo.getLegalPersonName());
            bizMerchantInfo.setRegisterAddress(bizMerchantInfo.getActiveAddress());
            bizMerchantInfo.setRegisterLatitude(bizMerchantInfo.getActiveLatitude());
            bizMerchantInfo.setRegisterLongitude(bizMerchantInfo.getActiveLongitude());
            if(bizMerchantInfo.getBusNature().equals("3")){
                bizMerchantInfo.setXwSigning("1");
                System.out.println(bizMerchantInfo.getLegalPersonName()+"进件已更新小微标识");
            }else if(bizMerchantInfo.getBusNature().equals("2")){
                bizMerchantInfo.setQySigning("1");
                System.out.println(bizMerchantInfo.getLegalPersonName()+"进件已更新企业标识");
            }
            bizMerchantInfo.setAppletSign("1");
            //存到自己的库里
            boolean save = bizMerchantInfoService.save(bizMerchantInfo);
            //推送审核成功消息
            String fanXianMess = bizMerchantInfo.getLegalPersonName()+"商户号:"+merchantNo+"审核成功";
            BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
            fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
            fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
            fanXianMessageRecords.setReadStatus(0); // 消息未读
            fanXianMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
            return AjaxResult.success("提交成功,待审核");
        } else {
            //推送审核成功消息
            String fanXianMess = bizMerchantInfo.getLegalPersonName() + "审核失败:" + desc;
            BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
            fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
            fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
            fanXianMessageRecords.setReadStatus(0); // 消息未读
            fanXianMessageRecords.setAdviceType(1); // 业务消息
            webSocketServer.sendInfo(merchantByMerchId.getUserId(), fanXianMessageRecords);// 发送消息
            if (null != data) {
                JSONObject mate = data.getJSONObject("mate");
                if (null != mate) {
                    desc = desc + ":" + mate.getString("msg");
                }
            }
            bizMerchantInfo.setInfoCompleted("0");
//            bizMerchantInfo.setMerchantKey(data.getString("merchantKey"));
//            bizMerchantInfo.setMasterKeys(data.getString("masterkeys"));
//            bizMerchantInfo.setValidationValue(data.getString("validationValue"));
            bizMerchantInfo.setAuditStatus("2");
            bizMerchantInfo.setMerchId(bizMerchantInfo.getMerchId());
            bizMerchantInfo.setMerchantDesc(desc);
            bizMerchantInfo.setCertificateType("1");
            bizMerchantInfo.setProductType("POS");
            bizMerchantInfo.setMccCode(bizMerchantInfo.getMccCd());
            bizMerchantInfo.setMerchantSubType("4");
            bizMerchantInfo.setMerchantType("1");
            bizMerchantInfo.setBankCardAccountType("1");
            bizMerchantInfo.setUserName(userName);
//            bizMerchantInfo.setMerchantLevel(data.getString("merchantLevel"));
            bizMerchantInfo.setRegisterTime(DateUtils.dateFormatString(new Date()));
            bizMerchantInfo.setClientServicePhoneNo(bizMerchantInfo.getBankCardPhone());
            bizMerchantInfo.setMerchantName(bizMerchantInfo.getLegalPersonName());
            bizMerchantInfo.setRegisterAddress(bizMerchantInfo.getActiveAddress());
            bizMerchantInfo.setRegisterLatitude(bizMerchantInfo.getActiveLatitude());
            bizMerchantInfo.setRegisterLongitude(bizMerchantInfo.getActiveLongitude());
            if(bizMerchantInfo.getBusNature().equals("3")){
                bizMerchantInfo.setXwSigning("1");
                System.out.println(bizMerchantInfo.getLegalPersonName()+"进件已更新小微标识");
            }else if(bizMerchantInfo.getBusNature().equals("2")){
                bizMerchantInfo.setQySigning("1");
                System.out.println(bizMerchantInfo.getLegalPersonName()+"进件已更新企业标识");
            }
            bizMerchantInfo.setAppletSign("1");
            //存到自己的库里
            boolean save = bizMerchantInfoService.save(bizMerchantInfo);
            System.out.println(bizMerchantInfo.getCertificateNo()+"进件失败返回小程序提示为:"+desc);
            return AjaxResult.error(bizMerchantInfo.getCertificateNo()+":"+desc);
        }
    }

    @Override
    public AjaxResult noSnMerchantInfo(String json){
        Map<String , String> map = PublicUtil.generateMap(json);
        String idCard = map.get("idCard");
        List<BizMerchantInfo> infos = bizMerchantInfoMapper.getNoSnMerchantInfo(idCard);
        for(BizMerchantInfo info : infos){
            if(info.getMerchantId() == null){
                info.setMerchantId("无");
            }
            if(info.getMerchantCode() == null){
                info.setMerchantCode("无");
            }
        }
        if(infos.size() > 0){
            return AjaxResult.success("商户信息",infos);
        }else{
            return AjaxResult.error("无商户信息");
        }

    }


    @Override
    public AjaxResult changeKdbMerchantId(String json){
        Map<String , String> map = PublicUtil.generateMap(json);
        String url = "http://152.136.252.115:8081/pos/merchantInfo/changePTMerchantId";
//        String url = "http://127.0.0.1:8081/pos/merchantInfo/changePTMerchantId";
        System.out.println("查开店宝商户号"+ JSONObject.toJSONString(map));
        String result = HttpUtil.doPostxxl(url, JSONObject.toJSONString(map));
        System.out.println("查开店宝商户号"+ JSONObject.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        if("200".equals(jsonObject.getString("code"))){
            BizMerchantInfo info = bizMerchantInfoMapper.getMerchantInfoByMerchantCode(map.get("merchantCode"));
            info.setMerchantId(jsonObject.getString("data"));
            this.saveOrUpdate(info);
            return AjaxResult.success("更新成功");
        }else{
           return AjaxResult.error("更新失败"+jsonObject.getString("msg"));
        }
    }

    @Override
    public AjaxResult bffr() throws ParseException {
        List<BizTransactionAmountEntity> sys = bizMerchantInfoMapper.selectTransData();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(BizTransactionAmountEntity sy1 :sys){
            SynchronizationDataDTO sy = new SynchronizationDataDTO();
            sy.setPos_sn(sy1.getPosSn());
            sy.setAddi_amount(sy1.getAddiAmount());
            sy.setAmnount(sy1.getAmnount());
            sy.setFee_name(sy1.getFeeName());
            sy.setHost_date(sdf.format(sy1.getHostDate()));
            sy.setMerchId(sy1.getMerchId());
            sy.setParentId(sy1.getParentId());
            sy.setUuid(sy1.getUuid());
            sy.setIsSecondExecute("1");
            bizTransactionAmountServicImpl.shareTheMoney(sy);
            System.out.println(sy1.getPosSn()+"-----"+sy1.getUuid());
        }

        return AjaxResult.success();
    }


    @Override
    public AjaxResult updateRate() {
        List<SysUser> users = bizMerchantInfoMapper.getUpdateRate();
        BigDecimal rate = new BigDecimal("0.11");
        for(SysUser user : users){
            System.out.println(user.getNickName()+"税率"+user.getRate());
            bizMerchantInfoMapper.updateRateByUserId(user.getUserId(), rate);
            Long merchId = bizMerchantInfoMapper.getMerchIdByUserId(user.getUserId());
            List<BizMerchParentRelated> childrens = bizMerchantInfoMapper.getChildrensBuParentId(merchId);
            for(BizMerchParentRelated child : childrens){
                Long  childMerchId = child.getChildId();
                Long userId = bizMerchantInfoMapper.getUserIdByMerchId(childMerchId);
                System.out.println("userId--------->"+userId);
                bizMerchantInfoMapper.updateRateByUserId(userId, rate);
            }
        }
        return AjaxResult.success();
    }



    @Override
    public AjaxResult receiveLHExamine(JSONObject json) {
        String posCode = json.getString("posCode"); // 机器号
        String desc = json.getString("desc"); // 审核描述
        BizMerchant bizMerchant = bizMerchantService.selectBizMerchantBySN(posCode);
        BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
        fanXianMessageRecords.setMsgContent(desc);// 消息内容
        fanXianMessageRecords.setMsgType(9); // 消息类型  返现   机具激活返现
        fanXianMessageRecords.setReadStatus(0); // 消息未读
        fanXianMessageRecords.setAdviceType(1); // 业务消息
        webSocketServer.sendInfo(bizMerchant.getUserId(), fanXianMessageRecords);// 发送消息
        return AjaxResult.success();
    }

    @Override
    public AjaxResult tttt() {
        List<BizMerchantInfo> infos = bizMerchantInfoMapper.getINfos();
        for(BizMerchantInfo info : infos){
            JSONObject params = new JSONObject();
            params.put("merchantCode",info.getMerchantCode());
            String result = HttpUtil.doPostxxl("http://127.0.0.1:8081/pos/merchantInfo/chaxunshanghuhao", JSONObject.toJSONString(params));
            JSONObject jsonObject = JSONObject.parseObject(result);
            try {
                String data = jsonObject.getString("data");
                JSONObject jsonObject11 = JSONObject.parseObject(data);
                String merchantId = jsonObject11.getString("merchantId");
                info.setMerchantId(merchantId);
                this.saveOrUpdate(info);
            }catch (Exception e){

            }

        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult updateFee(){
        List<BizMerchantInfo> infos = bizMerchantInfoMapper.getFeeInfos();
        int feeId = 10060;
        for(BizMerchantInfo info : infos){
            JSONObject params = new JSONObject();
            params.put("merchantCode",info.getMerchantCode());
            params.put("feeId",feeId);
            String result = HttpUtil.doPostxxl("http://127.0.0.1:8081/underLine/task/updateFee", JSONObject.toJSONString(params));
            JSONObject jsonObject = JSONObject.parseObject(result);
            if("200".equals(jsonObject.getString("code"))){
                System.out.println(info.getMerchantCode()+"修改费率成功");
                bizMerchantInfoMapper.updateSlienceRule(info.getMerchantCode());
                bizMerchantInfoMapper.updateFeeIdByMerchantNo(info.getMerchantCode(),Long.parseLong(String.valueOf(feeId)));
            }else{
                System.out.println(info.getMerchantCode()+"修改费率失败");
            }
        }
        return AjaxResult.success();
    }

    @Override
    public JSONObject appBackMerchantInfoList(BizMerchantInfo bizMerchantInfo) {
        JSONObject jsonObject = new JSONObject();
        String merchType = bizMerchantInfo.getMerchType();// 0直属商户 1渠道商户
        List<Long> merchIds = new ArrayList<Long>();
        BizMerchant merchant = bizMerchantService.getMerchantByUserId(bizMerchantInfo.getUserId());
        if("0".equals(merchType)){
            merchIds.add(merchant.getMerchId());
        }else{
            merchIds = bizMerchantInfoMapper.getMerchParentRelated(merchant.getMerchId());
        }
        bizMerchantInfo.setMerchIds(merchIds);
        String channel = bizMerchantInfo.getChannel();
        bizMerchantInfo.setPageNo((bizMerchantInfo.getPageNo()-1)*bizMerchantInfo.getPageSize());
        List<BizMerchantInfo> infoList = new ArrayList<BizMerchantInfo>();
        if(merchIds.size()>0){
            if("".equals(bizMerchantInfo.getSortType()) || null == bizMerchantInfo.getSortType()){
                bizMerchantInfo.setSortType("1");
            }
            infoList = bizMerchantInfoMapper.getNewMerchantInfoList(bizMerchantInfo);
        }
        jsonObject.put("code",200);
        jsonObject.put("msg","商户列表");
        jsonObject.put("list",infoList);
        jsonObject.put("count",infoList.size());
        return jsonObject;
    }


    @Override
    public AjaxResult appBackMerchantInfoDetail(BizMerchantInfo bizMerchantInfo) throws ParseException {
        MerchantDetailDTO merchantDetailDTO =  bizMerchantInfoMapper.getMerchantInfoDetailByMerchantCode(bizMerchantInfo.getMerchantCode());
        if("17".equals(merchantDetailDTO.getChannel())){
            merchantDetailDTO.setChannel("1");// 此处为显示费率, 将channel设置成1
            if(!"".equals(merchantDetailDTO.getPosCode()) && merchantDetailDTO.getPosCode() != null ){
                BizPosMachine bizPosMachine = posMachineService.getPosMachineBySnCode(merchantDetailDTO.getPosCode());
                if(bizPosMachine.getFee() != null){
                    BizMerchantFeeName bizMerchantFeeName = posTransactionNoticeMapper.selectFeeName(bizPosMachine.getFee());
                    merchantDetailDTO.setFeeValue(bizMerchantFeeName.getFeeValue());
                }else{
                    merchantDetailDTO.setFeeValue("未知");
                }
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(merchantDetailDTO.getPosCode() == null){// 没设备, 就没政策
            merchantDetailDTO.setIsBogus("0");
            merchantDetailDTO.setIsNotActive("0");
            merchantDetailDTO.setActiveAmount("0.00");
        }else{
            BizPosMachine bizPosMachine = posMachineService.getPosMachineBySnCode(merchantDetailDTO.getPosCode());
            //未激活政策
            if(bizPosMachine.getTemp1() == null || bizPosMachine.getTemp1() == 1L){// 有设备, 没未激活政策
                merchantDetailDTO.setIsNotActive("0");
            }else{
                UnFailureActiveTemplate unFailureActiveTemplate = unFailureActiveTemplateMapper.selectById(bizPosMachine.getTemp1());
                merchantDetailDTO.setIsNotActive("1");// 有设备, 有未激活政策
                //看是否绑定
                BizPosMachineStatusRecords bizPosMachineStatusRecords
                        = machineStatusRecordsService.selectBizPosMachineStatusRecordsBysnCode(merchantDetailDTO.getPosCode());
                if(bizPosMachineStatusRecords == null){
                    merchantDetailDTO.setActiveTimeStr("无");
                    merchantDetailDTO.setNotActiveDeduction(unFailureActiveTemplate.getDeductionPrice().toString());
                    merchantDetailDTO.setIsNotActiveEnough("未达标");//todo
                }else{
                    if(!bizPosMachineStatusRecords.getTime().contains("-")){
                        bizPosMachineStatusRecords.setTime(bizPosMachineStatusRecords.getTime().substring(0,4)
                                +"-"+bizPosMachineStatusRecords.getTime().substring(4,6)
                                +"-"+bizPosMachineStatusRecords.getTime().substring(6,8)+" 00:00:00");
                    }
                    Calendar rightNow = Calendar.getInstance();
                    rightNow.setTime(sdf.parse(bizPosMachineStatusRecords.getTime()));// 激活时间
                    rightNow.add(Calendar.DAY_OF_MONTH, unFailureActiveTemplate.getDays());// 天数
                    Date dt1 = rightNow.getTime();
                    merchantDetailDTO.setActiveTimeStr(sdf.format(dt1));
                    merchantDetailDTO.setNotActiveDeduction(unFailureActiveTemplate.getDeductionPrice().toString());
                    merchantDetailDTO.setIsNotActiveEnough("未达标");
                }
            }
            //伪激活政策
            if(bizPosMachine.getTemp2() == null || bizPosMachine.getTemp2() == 2L){// 有设备, 没伪激活政策
                merchantDetailDTO.setIsBogus("0");
            }else{
                UnFailureActiveTemplate unFailureActiveTemplate = unFailureActiveTemplateMapper.selectById(bizPosMachine.getTemp2());
                merchantDetailDTO.setIsBogus("1");// 有设备, 有伪激活政策
                //看是否绑定
                BizPosMachineStatusRecords bizPosMachineStatusRecords
                        = machineStatusRecordsService.selectBizPosMachineStatusRecordsBysnCode(merchantDetailDTO.getPosCode());
                merchantDetailDTO.setBogusExpireDay(unFailureActiveTemplate.getDays());
                merchantDetailDTO.setBogusActiveAmount(unFailureActiveTemplate.getTransAmount().toString());
                merchantDetailDTO.setBogusActiveDeduction(unFailureActiveTemplate.getDeductionPrice().toString());
                merchantDetailDTO.setIsBogusEnough("未达标");//todo
            }
            //激活返现金额
            AllocationRelation allocationRelation =
                    iAllocationRelationService.getInfoBySnAndMerchId(merchantDetailDTO.getPosCode(), bizPosMachine.getMerchId());
            merchantDetailDTO.setActiveAmount("0.00");
            if(allocationRelation != null && allocationRelation.getStandardCashback() != null){
                merchantDetailDTO.setActiveAmount(allocationRelation.getStandardCashback().toString());
            }
            //刷满返现政策
            if(bizPosMachine.getCustomerCashBackId() == null || bizPosMachine.getCustomerCashBackId() == 1L){
                merchantDetailDTO.setIsCashBack("0");
            }else{
                merchantDetailDTO.setIsCashBack("1");
                CustomerCashBackTemp customerCashBackTemp
                        = posMachineService.getCCBTPolicy(bizPosMachine.getCustomerCashBackId());
                merchantDetailDTO.setTransAmount(customerCashBackTemp.getCashAmount());
                merchantDetailDTO.setCashBackAmount(customerCashBackTemp.getBackAmount());
                if("0".equals(merchantDetailDTO.getCashBackStatus())){
                    merchantDetailDTO.setIsEnoughBack("未达标");
                }else{
                    merchantDetailDTO.setIsEnoughBack("已达标");
                }
            }
        }
        return AjaxResult.success("详情",merchantDetailDTO);
    }


    @Override
    public AjaxResult appBackPartnerList(BizMerchant bizMerchant) {
        BizMerchant merchant = bizMerchantService.getMerchantByUserId(bizMerchant.getUserId());
        merchant.setPageNooo((bizMerchant.getPageNo()-1)*bizMerchant.getPageSize());
        merchant.setPageSizeee(bizMerchant.getPageSize());
        List<Long> merchIds = new ArrayList<Long>();


        if(bizMerchant.getMerchName() == null ||  "".equals(bizMerchant.getMerchName())){
            if(bizMerchant.getMerchId() != null){
                merchant.setMerchId(bizMerchant.getMerchId());
            }
            merchIds = bizMerchantInfoMapper.getMerchParentRelated2(merchant.getMerchId(),merchant.getPageNooo(),merchant.getPageSizeee());
//            merchIds = bizMerchantInfoMapper.getMerchParentRelated2(merchant);
        }else{
            merchIds = bizMerchantService.getMerchantByNameLike(bizMerchant.getMerchName());
        }
        List<PartnerDetailDTO> list = new ArrayList<PartnerDetailDTO>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for(Long merchId : merchIds){
            BizMerchant merchTeam = bizMerchantService.getMerchantByMerchId(merchId);
            SysUser sysUser = sysUserMapper.selectUserByUserId(merchTeam.getUserId());
            PartnerDetailDTO partnerDetailDTO = new PartnerDetailDTO();
            partnerDetailDTO.setMerchId(merchId);
            partnerDetailDTO.setMerchName(merchTeam.getMerchName());
            partnerDetailDTO.setRegisterTime(sdf.format(sysUser.getCreateTime()));
            partnerDetailDTO.setLastLoginTime(sdf.format(sysUser.getLoginDate()));
            partnerDetailDTO.setPortrait(sysUser.getPortrait());
            partnerDetailDTO.setPhone(sysUser.getPhonenumber());
            partnerDetailDTO.setPhoneStr(new StringBuilder(sysUser.getPhonenumber()).replace(3, 7, "****").toString());
            partnerDetailDTO.setThisMonthTransAmount(new BigDecimal(sysUser.getThisMonthTransAmount()));
            partnerDetailDTO.setLastMonthTransAmount(new BigDecimal(sysUser.getLastMonthTransAmount()));
            int count = bizMerchantInfoMapper.getSnCountByMerchId(merchId);
            partnerDetailDTO.setSnCount(count);
            list.add(partnerDetailDTO);
        }
        return AjaxResult.success("代理团队",list);
    }

    @Override
    public BizChannel getChannelDataByChannel(String channel) {
        return bizMerchantInfoMapper.getChannelDataByChannel(channel);
    }

    @Override
    public SysUser getSysUserByMerchId(Long merchId) {
        return bizMerchantInfoMapper.getSysUserByMerchId(merchId);
    }

    @Override
    public void dailyDimension() {
        // 今日交易不等0
        List<BizMerchantInfo> list = bizMerchantInfoMapper.selectAllMerchantInfo();
        list.stream().forEach(e->{
            e.setTodayTransAmount(new BigDecimal(0.00));
            this.updateMerchantsInfoByMerchantCode(e);
        });
    }

    @Override
    public void monthDimension() {
        //
        List<BizMerchantInfo> list = bizMerchantInfoMapper.selectAllMerchantInfo();
        list.stream().forEach(e->{
            e.setLastMonthTransAmount(e.getThisMonthTransAmount());
            e.setThisMonthTransAmount(new BigDecimal(0.00));
            this.updateMerchantsInfoByMerchantCode(e);
        });
    }

    @Override
    public List<BizMerchantInfo> selectAllMerchantInfoList() {
        return bizMerchantInfoMapper.selectAllMerchantInfo();
    }

    @Override
    public BizMerchantInfo getMerchantInfoBySnAndSuccess(String posCode) {
        return bizMerchantInfoMapper.getMerchantInfoBySnAndSuccess(posCode);
    }

    @Override
    public AjaxResult echoFeeIdBySn(BizPosMachine bizPosMachine) {
        Double minFeeRate = iAllocationRelationService.getRelationByMaxLevelAndSn(bizPosMachine.getPosCode());
        if(minFeeRate == null){
            return AjaxResult.error("设备未划拨");
        }
        List<BizMercahntFeeNameDTO> list = bizMerchantInfoMapper.echoFeeIds(minFeeRate);
        return AjaxResult.success("费率列表",list);
    }




    @Override
    public JSONObject jlMerchantInfoNotice(BizJLMerchantInfo bizJLMerchantInfo) {
        System.out.println("嘉联商户参数"+bizJLMerchantInfo);
        BizMerchantInfo bizMerchantInfo = bizMerchantInfoMapper.getMerchantInfoByMerchantCode(bizJLMerchantInfo.getMerchNo());
        if(bizMerchantInfo == null ){
            bizMerchantInfo = new BizMerchantInfo();
        }
        bizMerchantInfo.setMerchantCode(bizJLMerchantInfo.getMerchNo());
        bizMerchantInfo.setPhone(bizJLMerchantInfo.getPhone());
        bizMerchantInfo.setLegalPersonName(bizJLMerchantInfo.getName());
        bizMerchantInfo.setCertificateNo(bizJLMerchantInfo.getSupplement_info());
        bizMerchantInfo.setPosCode(bizJLMerchantInfo.getPossn());
        bizMerchantInfo.setAuditStatus("3");
        bizMerchantInfo.setChannel("17");
        bizMerchantInfo.setMerchantDesc("成功");
        bizMerchantInfo.setInfoCompleted("1");
        bizMerchantInfo.setMerchantLevel("1");
        bizMerchantInfo.setChannelName("嘉联");
        bizMerchantInfo.setWhetherBinding("1");
        bizMerchantInfo.setMerchantShortHand(bizJLMerchantInfo.getName());
        BizPosMachine bizPosMachine = bizPosMachineMapper.selectPosMachineBySn(bizJLMerchantInfo.getPossn());
        if(bizPosMachine != null){
            bizMerchantInfo.setMerchId(bizPosMachine.getMerchId());
        }else{
            System.out.println(bizJLMerchantInfo.getPossn()+"此设备未入库");
        }
        bizMerchantInfo.setRegisterTime(bizJLMerchantInfo.getBindTime());
        bizMerchantInfoService.saveOrUpdate(bizMerchantInfo);

        BizPosMachineStatusRecords bizPosMachineStatusRecords=new BizPosMachineStatusRecords();
        bizPosMachineStatusRecords.setSnCode(bizJLMerchantInfo.getPossn());
        bizPosMachineStatusRecords.setMerchantId(bizJLMerchantInfo.getMerchNo());
        bizPosMachineStatusRecords.setTime(bizJLMerchantInfo.getBindTime());
        bizPosMachineStatusRecords.setName(bizJLMerchantInfo.getName());
        //新增激活表信息
        bizPosMachineStatusRecordsMapper.insertBizPosMachineStatusRecords(bizPosMachineStatusRecords);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ret_code","00");
        return jsonObject;
    }

    @Override
    public AjaxResult addChannelAbout(BizChannel bizChannel) {
        // 渠道表
        BizChannel channelOld = bizMerchantInfoMapper.getChannelDataByChannel(bizChannel.getChannelId().toString());
        if(channelOld != null){
            return AjaxResult.error("此渠道已存在");
        }
        bizMerchantInfoMapper.insertNewChannel(bizChannel);
        // 分润钱包
        List<BizMerchant> bizMerchantList = bizMerchantService.getAllMerchants();
        for(BizMerchant bizMerchant : bizMerchantList){
            SysUser sysUser = sysUserMapper.selectUserByUserId(bizMerchant.getUserId());
            BizWalletNew bizWalletNew = iBizWalletNewService.getWalletNewByUserIdAndChannel(bizMerchant.getUserId(),bizChannel.getChannelId());
            if(bizWalletNew == null){
                bizWalletNew = new BizWalletNew();
                bizWalletNew.setUserId(bizMerchant.getUserId());
                bizWalletNew.setUserName(bizMerchant.getMerchName());
                bizWalletNew.setDeptId(sysUser.getDeptId());
                bizWalletNew.setDeptName(sysUser.getDeptName());
                bizWalletNew.setChannelId(bizChannel.getChannelId());
                bizWalletNew.setChannelName(bizChannel.getChannelName());
                bizWalletNew.setProfitAmount(BigDecimal.ZERO);
                bizWalletNew.setRewardAmount(BigDecimal.ZERO);
                bizWalletNew.setWalletAmount(BigDecimal.ZERO);
                bizWalletNew.setActivityIntegral(0l);
                bizWalletNew.setWalletAmount(BigDecimal.ZERO);
                bizWalletNew.setWithdrawalServiceAmount(BigDecimal.ZERO);
                bizWalletNew.setCreateTime(new Date());
                iBizWalletNewService.saveOrUpdate(bizWalletNew);
                System.out.println(bizMerchant.getMerchName()+","+bizChannel.getChannelName()+"渠道钱包增加成功");
            }else{
                System.out.println(bizMerchant.getMerchName()+","+bizChannel.getChannelName()+"此渠道已添加过分润钱包");
            }
            // 奖励钱包
            AizWithdrawalWallet aizWithdrawalWallet =
                    iBizWalletNewService.getWithdrawalWalletByUserIdAndChannelId(bizMerchant.getUserId(),bizChannel.getChannelId());
            if(aizWithdrawalWallet == null){
                aizWithdrawalWallet = new AizWithdrawalWallet();
                aizWithdrawalWallet.setUserId(bizMerchant.getUserId());
                aizWithdrawalWallet.setUserName(bizMerchant.getMerchName());
                aizWithdrawalWallet.setDeptId(sysUser.getDeptId());
                aizWithdrawalWallet.setDeptName(sysUser.getDeptName());
                aizWithdrawalWallet.setAmount(BigDecimal.ZERO);
                aizWithdrawalWallet.setChannelId(bizChannel.getChannelId());
                aizWithdrawalWallet.setChannelName(bizChannel.getChannelName());
                aizWithdrawalWallet.setCreateTime(new Date());
                iBizWalletNewService.insertWithdrawalWallet(aizWithdrawalWallet);
                System.out.println(bizMerchant.getMerchName()+","+bizChannel.getChannelName()+"添加奖励钱包成功");
            }else{
                System.out.println(bizMerchant.getMerchName()+","+bizChannel.getChannelName()+"此渠道已添加过奖励钱包");
            }
            // 累计交易分润
            AizStatisticalMerchant aizStatisticalMerchant =
                         iAizStatisticalMerchantService.getAizStatisticalsByUserIdAndChannel(bizMerchant.getUserId(),bizChannel.getChannelId());
            if(aizStatisticalMerchant == null){
                aizStatisticalMerchant = new AizStatisticalMerchant();
                aizStatisticalMerchant.setUserId(bizMerchant.getUserId());
                aizStatisticalMerchant.setChannelId(Integer.parseInt(bizChannel.getChannelId().toString()));
                aizStatisticalMerchant.setChannelName(bizChannel.getChannelName());
                aizStatisticalMerchant.setTotalProfitAmount(0.00);
                aizStatisticalMerchant.setYearProfitAmount(0.00);
                aizStatisticalMerchant.setLastMonthProfitAmount(0.00);
                aizStatisticalMerchant.setThisMonthProfitAmount(0.00);
                aizStatisticalMerchant.setTodayProfitAmount(0.00);
                aizStatisticalMerchant.setTotalTransAmount(0.00);
                aizStatisticalMerchant.setYearTransAmount(0.00);
                aizStatisticalMerchant.setLastMonthTransAmount(0.00);
                aizStatisticalMerchant.setThisMonthTransAmount(0.00);
                aizStatisticalMerchant.setTodayTransAmount(0.00);
                aizStatisticalMerchant.setYesterdayTransAmount(0.00);
                aizStatisticalMerchant.setYesterdayProfitAmount(0.00);
                iAizStatisticalMerchantService.saveOrUpdate(aizStatisticalMerchant);
                System.out.println(bizMerchant.getMerchName()+","+bizChannel.getChannelName()+"添加过分渠道统计成功");
            }else{
                System.out.println(bizMerchant.getMerchName()+","+bizChannel.getChannelName()+"此渠道已添加过分渠道统计");
            }
        }
        return AjaxResult.success("success");
    }



    public String sendMessage(String verifyCode,String phone,Long deptId){
        BizSms bizSms = bizMerchantInfoMapper.getSmsByDeptId(deptId);
        if(bizSms == null){
            return "No msg template";
        }
        JSONObject map = new JSONObject();
        map.put("appid",bizSms.getAppid());
        map.put("content",bizSms.getContent()+verifyCode+".");
        map.put("to",phone);
        map.put("signature",bizSms.getSignature());
        System.out.println("地址"+bizSms.getSmsUrl());
        System.out.println("参数"+map.toString());
        String result = PublicUtil.sendSms(bizSms.getSmsUrl(),map);
        JSONObject resStr = JSONObject.parseObject(result);
        if("success".equals(resStr.get("status"))){
            return "success";
        }else{
            return "failure";
        }
    }

    public static boolean isChinese(String str) {
        return str.matches("[\u4e00-\u9fa5]+");
    }

    @Override
    public AjaxResult slientMerchantInfo(BizMerchantInfo bizMerchantInfo) {
        if(isChinese(bizMerchantInfo.getQueryStr())){
            bizMerchantInfo.setLegalPersonName(bizMerchantInfo.getQueryStr());
        }else{
            bizMerchantInfo.setPosCode(bizMerchantInfo.getQueryStr());
        }
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        BizMerchant bizMerchant = bizMerchantService.getMerchantByUserId(sysUser.getUserId());
        bizMerchantInfo.setMerchId(bizMerchant.getMerchId());
        bizMerchantInfo.setPageBegin((bizMerchantInfo.getPageNo()-1)*bizMerchantInfo.getPageSize());
        bizMerchantInfo.setPageEnd(bizMerchantInfo.getPageSize());
        List<BizMerchantInfo> infoList = bizMerchantInfoMapper.getSilentMerchantInfo(bizMerchantInfo);
        return AjaxResult.success("沉默商户",infoList);
    }

    @Override
    public AjaxResult unActiveMerchantInfo(BizMerchantInfo bizMerchantInfo) {
        if(isChinese(bizMerchantInfo.getQueryStr())){
            bizMerchantInfo.setLegalPersonName(bizMerchantInfo.getQueryStr());
        }else{
            bizMerchantInfo.setPosCode(bizMerchantInfo.getQueryStr());
        }
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        BizMerchant bizMerchant = bizMerchantService.getMerchantByUserId(sysUser.getUserId());
        bizMerchantInfo.setPageBegin((bizMerchantInfo.getPageNo()-1)*bizMerchantInfo.getPageSize());
        bizMerchantInfo.setPageEnd(bizMerchantInfo.getPageSize());
        bizMerchantInfo.setMerchId(bizMerchant.getMerchId());
        List<BizMerchantInfo> infoList = bizMerchantInfoMapper.getUnActiveMerchantInfo(bizMerchantInfo);
        return AjaxResult.success("未激活商户",infoList);
    }

    @Override
    public AjaxResult failureActiveMerchantInfo(BizMerchantInfo bizMerchantInfo) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if(isChinese(bizMerchantInfo.getQueryStr())){
            bizMerchantInfo.setLegalPersonName(bizMerchantInfo.getQueryStr());
        }else{
            bizMerchantInfo.setPosCode(bizMerchantInfo.getQueryStr());
        }
        BizMerchant bizMerchant = bizMerchantService.getMerchantByUserId(sysUser.getUserId());
        bizMerchantInfo.setPageBegin((bizMerchantInfo.getPageNo()-1)*bizMerchantInfo.getPageSize());
        bizMerchantInfo.setPageEnd(bizMerchantInfo.getPageSize());
        bizMerchantInfo.setMerchId(bizMerchant.getMerchId());
        List<BizMerchantInfo> infoList = bizMerchantInfoMapper.getFailureActiveMerchantInfo(bizMerchantInfo);
        return AjaxResult.success("伪激活商户",infoList);
    }

    @Override
    public void silenceMerchantInfo() throws ParseException {
        List<BizMerchantInfo> infoList = bizMerchantInfoMapper.getMerchantInfos();
        for(BizMerchantInfo info : infoList){
            if(info.getPosCode() == null || "".equals(info.getPosCode())){
                info.setIsSilence("10");
                info.setSilenceDays(0);
                bizMerchantInfoService.saveOrUpdate(info);
            }else{
                //查出sn最后交易时间
                Date lastTransdate = BizMerchTransactionsService.selectLastTransData(info.getPosCode());
                if(lastTransdate == null){//没交易
                    //查询绑定日期
                    BizPosMachineStatusRecords bizPosMachineStatusRecords =
                            bizPosMachineStatusRecordsMapper.selectBizPosMachineStatusRecordsBysnCode(info.getPosCode());
                    if(bizPosMachineStatusRecords == null){// 没绑定
                        info.setIsSilence("10");
                        info.setSilenceDays(0);
                        bizMerchantInfoService.saveOrUpdate(info);
                    }else{// 绑定  没交易/没激活
                        if(!bizPosMachineStatusRecords.getTime().contains("-")){
                            bizPosMachineStatusRecords.setTime(bizPosMachineStatusRecords.getTime().substring(0,4)
                                    +"-"+bizPosMachineStatusRecords.getTime().substring(4,6)
                                    +"-"+bizPosMachineStatusRecords.getTime().substring(6,8)+" 00:00:00");
                        }
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        executeSilenceMerchantInfo(info,sdf.parse(bizPosMachineStatusRecords.getTime()));
                    }
                }else{// 有交易的,  查询最后交易距今多少天
                    executeSilenceMerchantInfo(info,lastTransdate);
                }
            }
        }
    }

    private void executeSilenceMerchantInfo(BizMerchantInfo info,Date date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int days = getDaysBetween(sdf.format(date),sdf.format(new Date()));
        if(days < 30){
            info.setIsSilence("10");
            info.setSilenceDays(days);
        }else if(days < 60) {
            info.setIsSilence("30");
            info.setSilenceDays(days);
        }else if(days < 90) {
            info.setIsSilence("60");
            info.setSilenceDays(days);
        }else{
            info.setIsSilence("90");
            info.setSilenceDays(days);
        }
        bizMerchantInfoService.saveOrUpdate(info);
    }

    public static int getDaysBetween(String startDateStr, String endDateStr) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = format.parse(startDateStr);
        Date endDate = format.parse(endDateStr);
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(startDate);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endDate);
        int days = 0;
        while (startCalendar.before(endCalendar)) {
            startCalendar.add(Calendar.DAY_OF_MONTH, 1);
            days++;
        }
        return days;
    }


    @Override
    public void selectUnActiveMerchantInfo() throws ParseException {
        List<BizPosMachineStatusRecords> records = bizPosMachineStatusRecordsMapper.selectAllUnActiveRecords();
         for(BizPosMachineStatusRecords bizPosMachineStatusRecords : records){
            if(!bizPosMachineStatusRecords.getTime().contains("-")){
                bizPosMachineStatusRecords.setTime(bizPosMachineStatusRecords.getTime().substring(0,4)
                        +"-"+bizPosMachineStatusRecords.getTime().substring(4,6)
                        +"-"+bizPosMachineStatusRecords.getTime().substring(6,8)+" 00:00:00");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            BizMerchantInfo info = bizMerchantInfoMapper.getMerchantInfoByMerchantCode(bizPosMachineStatusRecords.getMerchantId());
            int days = getDaysBetween(bizPosMachineStatusRecords.getTime(),sdf.format(new Date()));
            if(days < 30){
                info.setIsUnActive("0");
                info.setUnActiveDays(days);
            }else if(days < 60) {
                info.setIsUnActive("30");
                info.setUnActiveDays(days);
            }else if(days < 90) {
                info.setIsUnActive("60");
                info.setUnActiveDays(days);
            }else{
                info.setIsUnActive("90");
                info.setUnActiveDays(days);
            }
            bizMerchantInfoService.saveOrUpdate(info);
        }
    }


    @Override
    public void selectFailureActiveMerchantInfo() throws ParseException {
        List<BizPosMachineStatusRecords> records = bizPosMachineStatusRecordsMapper.selectAllActiveRecords();
        for(BizPosMachineStatusRecords record : records){
            //查询模板  拿到模板天数,  模板金额 , 从激活时间算 ,到 模板天数转化的日期内 ,是否大于模板金额
            UnFailureActiveTemplate unFailureActiveTemplate = unFailureActiveTemplateMapper.selectById(record.getTemp2());
            int tempDays = unFailureActiveTemplate.getDays();//模板天数
            BigDecimal tempAmount = unFailureActiveTemplate.getTransAmount();//模板金额
            String activeTime = record.getActiveTime();//激活日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(sdf.parse(activeTime));
            rightNow.add(Calendar.DAY_OF_MONTH, tempDays);
            String expireDate = sdf.format(rightNow.getTime());
            BigDecimal transAmount = BizMerchTransactionsService.getTransAmount(record.getMerchantId(),activeTime,expireDate);
            BizMerchantInfo info = bizMerchantInfoMapper.getMerchantInfoByMerchantCode(record.getMerchantId());
            int days = getDaysBetween(activeTime,sdf.format(new Date()));
            if(transAmount.compareTo(tempAmount) > 0){
                info.setIsFailureActive("0");
                info.setFailureActiveDays(days);
            }else{
                if(days < 60) {
                    info.setIsFailureActive("30");
                    info.setFailureActiveDays(days);
                }else if(days < 90) {
                    info.setIsFailureActive("60");
                    info.setFailureActiveDays(days);
                }else{
                    info.setIsFailureActive("90");
                    info.setFailureActiveDays(days);
                }
            }
            bizMerchantInfoService.saveOrUpdate(info);
        }
    }

    @Override
    public void updateTransAmount(BizMerchantInfo info) {
        bizMerchantInfoMapper.updateTransAmount(info);
    }

    @Override
    public void updateTransAmount1(BizMerchantInfo info) {
        bizMerchantInfoMapper.updateTransAmount1(info);
    }

    @Override
    public void executeCreateFlowTask() throws ParseException {
        List<BizMerchantInfo> infoList= bizMerchantInfoMapper.getLsMerchantInfo();
        for(BizMerchantInfo info : infoList){
            BizPosMachine bizPosMachine = bizPosMachineMapper.selectPosMachineBySn(info.getPosCode());
            if("1".equals(bizPosMachine.getFlowLoop())//循环收取
                    && !"0".equals(bizPosMachine.getSimAmt()) && bizPosMachine.getSimAmt() != null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date beginTime = sdf.parse(info.getRegisterTime());
                //获取
                if(info.getSecondFlowReceiveTime() != null){
                    beginTime = info.getSecondFlowReceiveTime();
                }
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(beginTime);
                int days = bizPosMachine.getNextFlowDays();
                if(days == 0) days = 180;
                rightNow.add(Calendar.DAY_OF_MONTH, days);
                String expireDate = sdf.format(rightNow);
                String today = sdf.format(new Date());
                if(expireDate.equals(today)){
                    //创建二次流量费
                    JSONObject llParams = new JSONObject();
                    llParams.put("merchantCode",info.getMerchantCode());
                    llParams.put("posCode",bizPosMachine.getPosCode());
                    llParams.put("simAmt",bizPosMachine.getSimAmt());
                    String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getCreateSecondFlowFee(), JSONObject.toJSONString(llParams));
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if("200".equals(jsonObject.getString("code"))){
                        System.out.println(bizPosMachine.getPosCode()+"流量费创建成功");
                    }else{
                        System.out.println(bizPosMachine.getPosCode()+"流量费创建失败"+jsonObject.getString("msg"));
                    }
                }
            }
        }
    }

    @Override
    public List<AllocationRelation> executeQueryTrans(BizMerchantInfo bizMerchantInfo) {
        List<AllocationRelation> allocationRelationList = bizMerchantInfoMapper.getAllocationRList(bizMerchantInfo);
        return allocationRelationList;
    }

}
